;

How to Remove a Property From a Javascript Object


Tutorialsrack 11/05/2021 Jquery Javascript

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

Example 1: Using delete Operator

The JavaScript delete operator removes a given property from an object. On successful deletion, it will return true, else it returns false.

Example 1: Using delete Operator
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

Example 2: Using Spread operator

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:

Example 2: Using Spread operator
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

Example 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. It returns a Boolean indicating whether or not the property was successfully deleted.

Example 3:  Using Reflect.deleteProperty() function
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

Example 4: Using Underscore/Lodash Library

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.

Example 4: Using Underscore/Lodash Library
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!


Related Posts



Comments

Recent Posts
Tags