Object.keys
returns an array of an object's enumerable property names.
Enumerable properties are properties set "via simple assignment or via a property initializer". Since JavaScript objects have a lot of additional properties (e.g. constructor
, __proto__
), we don't want to include these types of properties when operating on our object. They can be accessed directly, of course, but won't be included when iterating over properties.
The usage is simple, see the following example:
const obj = {
name: 'Levi Coffin',
birthdate: '10/28/1798',
city: 'Newport',
state: 'Indiana'
};
Object.keys(obj) // => [ 'name', 'birthdate', 'city', 'state' ]
To iterate through the object's properties, we can use forEach
:
Object.keys(obj).forEach(key => {
console.log(key);
});
Or for...of
:
for (let key of Object.keys(obj)) {
console.log(key);
}
And to get the corresponding value, we can use the key for reference. Although, at this point, you ought to use Object.entries
from the previous step:
for (let key of Object.keys(obj)) {
let value = obj[key];
console.log(key, value);
}
When should I use Object.keys
?
As the method name implies, you should use Object.keys
when you're only interested in the keys (property names) of an object. If you're also interested in the values, Object.entries
is probably the right tool.
Object.keys
is especially useful when we're using an object to map data. Consider the following object:
const nameAgeMap = {
'Tom': 30,
'Susan': 28,
'Rob': 35,
'Claire': 22
};
Object.keys
gives us access to an array of names.
Object.keys(nameAgeMap) // => [ 'Tom', 'Susan', 'Rob', 'Claire' ]