/

The Object keys() method

The Object keys() method

Learn everything you need to know about the JavaScript keys() method of the Object object.

The Object.keys() method takes an object as an argument and returns an array of all its (own) enumerable properties.

1
2
3
4
5
6
7
const car = {
color: 'Blue',
brand: 'Ford',
model: 'Fiesta'
}

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

Here, “enumerable properties” refers to properties whose internal enumerable flag is set to true, which is the default behavior. To dive deeper into this concept, you can refer to the documentation on enumerability and ownership of properties on MDN.

One practical use-case for the Object.keys function is to create a copy of an object that excludes a specific property:

1
2
3
4
5
6
7
8
9
10
11
12
const car = {
color: 'blue',
brand: 'Ford'
}
const prop = 'color'

const newCar = Object.keys(car).reduce((object, key) => {
if (key !== prop) {
object[key] = car[key]
}
return object
}, {})

tags: [“JavaScript”, “Object.keys”, “enumerable properties”, “copy object”]