Javascript Object.keys()

The JavaScript Object.keys() method returns an array of a given object's own enumerable property names.

The syntax of the keys() method is:

Object.keys(obj)

The keys() method, being a static method, is called using the Object class name.


keys() Parameters

The keys() method takes in:

  • obj - The object whose enumerable properties are to be returned.

Return value from keys()

  • Returns an array of strings that represent all the enumerable properties of the given object.

Note: The ordering of the properties is the same as that when looping over them manually.


Example: Using Object.keys()

// Array objects
const arr = ["A", "B", "C"];
console.log(Object.keys(arr)); // ['0', '1', '2']

// array-like objects
const obj = { 65: "A", 66: "B", 67: "C" };
console.log(Object.keys(obj)); // ['65', '66', '67']

// random key ordering
const obj1 = { 42: "a", 22: "b", 71: "c" };
console.log(Object.keys(obj1)); // ['22', '42', '71']

// string => from ES2015+, non objects are coerced to object
const string = "code";
console.log(Object.keys(string)); // [ '0', '1', '2', '3' ]

Output

[ '0', '1', '2' ]
[ '65', '66', '67' ]
[ '22', '42', '71' ]
[ '0', '1', '2', '3' ]

Recommended Reading: Javascript Object entries()