Remove a property from an object in JavaScript
This post will discuss how to remove a property from an object in JavaScript.
1. Using Delete Operator
The delete operator removes a given property from an object, returning true or false as appropriate on success and failure.
|
1 2 3 4 5 6 7 8 |
var person = { name: 'John', age: 23, sex: 'Male' }; delete person.age; console.log(person); /* Output: { name: 'John', sex: 'Male' } */ |
2. Using Spread operator
With ES6, you can use the object literal destructuring assignment to unpack properties from objects into distinct variables. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
var person = { name: 'John', age: 23, sex: 'Male' }; const { age, ...rest } = person; console.log(rest); /* Output: { name: 'John', sex: 'Male' } */ |
Note this will create a new object. You can even do this without a declaration by using parentheses ( … ) around the assignment statement.
|
1 2 3 4 5 6 7 8 |
var person = { name: 'John', age: 23, sex: 'Male' }; ({ age, ...rest } = person); console.log(rest); /* Output: { name: 'John', sex: 'Male' } */ |
3. Using Reflect.deleteProperty() function
The Reflect.deleteProperty() method is used to delete a property on an object. It is identical to the delete operator.
|
1 2 3 4 5 6 7 8 |
var person = { name: 'John', age: 23, sex: 'Male' }; Reflect.deleteProperty(person, 'age'); console.log(person); /* Output: { name: 'John', sex: 'Male' } */ |
4. Using Underscore/Lodash Library
If you’re already using the Underscore or Lodash library, consider using the _.omit method. It creates a copy of the object without the specified property.
|
1 2 3 4 5 6 7 8 9 10 |
var _ = require('underscore'); var person = { name: 'John', age: 23, sex: 'Male' }; person = _.omit(person, 'age'); console.log(person); /* Output: { name: 'John', sex: 'Male' } */ |
That’s all about removing a property from an object in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)