The Object keys() method
By Flavio Copes
Learn how JavaScript Object.keys() returns an array of an object's own enumerable string property names, and which properties it leaves out.
Object.keys() returns an array containing an object’s own enumerable string property names.
const car = {
color: 'blue',
brand: 'Ford',
model: 'Fiesta'
}
Object.keys(car) //['color', 'brand', 'model']
You can use the result with any array operation:
for (const key of Object.keys(car)) {
console.log(key, car[key])
}
See the MDN Object.keys() reference and the ECMAScript specification for the exact enumeration order and coercion rules.
Which properties are included?
Object.keys() only includes properties that are:
- owned directly by the object
- enumerable
- keyed by strings
It leaves out inherited properties, non-enumerable properties, and Symbol-keyed properties:
const id = Symbol('id')
const vehicle = { wheels: 4 }
const car = Object.create(vehicle)
car.brand = 'Ford'
car[id] = 123
Object.defineProperty(car, 'serialNumber', {
value: 'ABC123',
enumerable: false
})
Object.keys(car) //['brand']
Use these related methods when you need different data:
Object.values()returns the corresponding valuesObject.entries()returns[key, value]pairsObject.getOwnPropertyNames()also includes non-enumerable string keysObject.getOwnPropertySymbols()returns own Symbol keys
Strings are converted to wrapper objects, so their character indexes are returned:
Object.keys('hello') //['0', '1', '2', '3', '4']
Passing null or undefined throws a TypeError.
Related posts about js: