The Object keys() method

By

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. Pass it an object, and you get back the list of its keys:

const car = {
  color: 'blue',
  brand: 'Ford',
  model: 'Fiesta'
}

Object.keys(car) //['color', 'brand', 'model']

Why do we need it? Objects don’t have array methods. You can’t call map() or filter() on an object, and there’s no length property to count its properties. Object.keys() gives you a plain array, and from there you can use everything arrays offer.

Counting the properties of an object is a common use:

Object.keys(car).length //3

So is looping over an object:

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:

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']

wheels is inherited from vehicle, serialNumber is not enumerable, and the Symbol key is skipped. Only brand makes the cut.

Use these related methods when you need different data:

What order are the keys in?

The order is defined, but it’s not always insertion order. Keys that look like array indexes come first, sorted in ascending numeric order. All other string keys follow in insertion order:

const scores = { 10: 'ten', 2: 'two', player: 'Flavio' }

Object.keys(scores) //['2', '10', 'player']

This is a common pitfall. If you build an object with numeric keys and expect to read them back in the order you added them, you won’t. When insertion order matters, use a Map instead, which always preserves it.

Edge cases

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: