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.
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:
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
}, {})