Understanding Object.keys in JavaScript

Understanding Object.keys in JavaScript


Object.keys is a method in JavaScript that returns an array whose values are the keys in an object. The object is used as an argument in the method. The order of the values in the array is the same as the order of keys in the object.

Syntax

Object.keys(object);

This method can be used on arrays and key-value objects, though it is usually used with the latter.

With arrays, we get the indexes which are the keys in getting the values i.e arr[index] == arr[key] while for objects, we get the names of keys in the key-value pairs.

Examples

let arr = ['codesource', 'io', 'code'];
let obj = {
    name: 'codesource',
    website: 'code-source.tempurl.host',
    type: 'code'
};

let arrKeys = Object.keys(arr);
let objKeys = Object.keys(obj);

console.log(arrKeys, objKeys);

// Expected output
// ["0", "1", "2"] 
// ["name", "website", "type"]

As said above, the output follows the same order declared for the object.

It allows us to easily loop through objects easily. It allows us to perform array operations such as map() and forEach() on objects (with the keys), though with an intermediary operation – calling the method.

In objKeys above, we can easily loop through the object and print out the values.

objKeys.forEach(key => {
    console.log(obj[key]);
    // or any other operation
    // like DOM or calculations
})

Notes

  • In ES5, if the argument is not an object, it returns a TypeError.
  • In ES2015, if the argument is not an object, it will be coerced to an object.

For example, a string;

let str = 'code';
Object.keys(str);
// For ES5 - TypeError: str is not an object;
// For ES2015 - ["0", "1", "2", "3"]

The output in ES2015 are the keys of the values in the string.

For more information, check out the MDN Documentation


Share on social media

//