/

How to Remove a Property from a JavaScript Object

How to Remove a Property from a JavaScript Object

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:

1
2
3
4
const car = {
color: 'blue',
brand: 'Ford'
}

You can delete a property from this object by using:

1
delete car.brand

Delete a property from an object in JavaScript

The delete keyword can also be expressed as:

1
2
3
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:

Iterate over the object

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():

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

Create a new object without mutating the original

Tags: JavaScript, object manipulation, delete property, undefined, mutability, immutability