In this article, you’ll learn how to remove a property from a javascript object. There are various ways to remove a property from a javascript object.
Here are some example to remove a property from a javascript object
The JavaScript delete
operator removes a given property from an object. On successful deletion, it will return true
, else it returns false
.
const Employee = {
firstname: 'John',
lastname: 'Doe',
gender: 'Male',
age: 45
};
console.log('Age: '+ Employee.age);
// expected output: "Age: 45"
delete Employee.age;
// property deleted
console.log(Employee.age);
// expected output: undefined
With ES6, You could use Rest syntax in Object Destructuring to get all the properties except age
to a rest variable. The example demonstrated below:
const Employee = {
firstname: 'John',
lastname: 'Doe',
gender: 'Male',
age: 45
};
console.log('Age: '+ Employee.age);
// expected output: "Age: 45"
const { age, ...rest } = Employee;
console.log(rest);
// Output: { firstname: "John", gender: "Male", lastname: "Doe" }
console.log(rest.age);
// expected output: undefined
The Reflect.deleteProperty()
method is used to delete a property on an object. It is identical to the delete operator. It returns a Boolean indicating whether or not the property was successfully deleted.
const Employee = {
firstname: 'John',
lastname: 'Doe',
gender: 'Male',
age: 45
};
console.log('Age: '+ Employee.age);
// expected output: "Age: 45"
Reflect.deleteProperty(Employee, 'age');
console.log(Employee);
// Output: { firstname: "John", gender: "Male", lastname: "Doe" }
console.log(Employee.age);
// expected output: undefined
If you’re already using the Underscore or Lodash library, consider using the _.omit
method. The _.omit()
method is used to return a copy of the object without the specified property.
var Employee = {
firstname: 'John',
lastname: 'Doe',
gender: 'Male',
age: 45
};
console.log('Age: '+ Employee.age);
// expected output: "Age: 45"
Employee = _.omit(Employee, 'age');
console.log(Employee);
// Output: { firstname: "John", gender: "Male", lastname: "Doe" }
console.log(Employee.age);
// expected output: undefined
I hope this article will help you to understand how to remove a property from a javascript object.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments