Deleting a property from a JavaScript object can be done using the delete
keyword. Alternatively, you can set the property to undefined
. This article discusses these options and provides a suggested solution.
The most semantically correct way to remove a property from an object is to use the delete
keyword. For example, given the object:
const car = {
color: 'blue',
brand: 'Ford'
}
You can delete a property from this object by using:
delete car.brand
The delete
keyword can also be expressed as:
delete car['brand']
delete car.brand
delete newCar['brand']
Another option to remove a property is to set it to undefined
. While this option can improve performance, especially when operating on a large number of objects in loops, it is important to note that the property is not actually deleted from the object. Its value is simply wiped. For example:
However, if mutability is a concern, and you want to completely remove the property without mutating the original object, you can create a new object by copying all properties from the old object, except the one you want to remove. This can be achieved using Object.keys()
:
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 manipulation, delete property, undefined, mutability, immutability