Use the delete
keyword to remove a property or attribute from an object. This is semantically correct.
The object
const car = {
color: 'blue',
brand: 'Ford'
}
You can delete an object’s property by using
delete car.brand
It can also be expressed as:
delete car['brand']
delete car.brand
delete newCar['brand']
Setting a property to undefined
You can set the property undefined
. if you have to optimize this operation, such as when you are working on large numbers of objects in loops.
It is more than 50x slower than a simple reassignment of undefined
, because delete
performance is slower.
Keep in mind, however, that the property cannot be deleted from an object. Although its value has been wiped away, it is still available if the object is iterated:
You can still use delete
very quickly. However, you shouldn’t look into this type of performance issue unless you have a good reason. It’s better to have clearer semantics and more functionality.
Remove a property without mutating the object
Mutability can be a problem. You can create a new object by copying all properties from the previous object, except the one that you wish to delete.
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
}, {})