This post will describe the method for removing the property from the selected object.
Remove/Eliminate a Property From an Object
For the purpose of eliminating a property from an object, use the following approaches:
Method 1: Remove/Eliminate a Property From an Object Using “delete” Operator
You can utilize the “delete” operator for eliminating a property from a particular object. More specifically, you must repeat the delete operator in the same function if you want to delete several properties.
Syntax
Follow the provided syntax to delete the property from a JavaScript object:
Or
Example
Create an object:
name: 'John',
age: 30,
rollno: 15
};
Use the delete operator to delete the property “rollno” of an object:
It can be seen that the “rollno” has been successfully deleted from the specified object:
Method 2: Remove/Eliminate a Property From a JavaScript Object Using filter() Method
You can also use the “filter()” method to remove a property from an object in JavaScript. It makes a new array with elements that satisfy a function’s condition.
Syntax
Follow the mentioned syntax for the filter() method:
Example
Create an object called “info”:
firstName: 'John',
lastName: 'Cove',
age: 27,
rollno: 18
};
Now, create an empty object called “filteredObj” that contains the values that pass the given condition:
Invoke the filter() method with the keys of the object, and fetch the properties that are not equal to the key “lastName”, and store it in an empty object:
if (property !== 'lastName') {
filteredObj[property] = info[property]
}
})
Print the filtered object on the console:
It can be observed that the property “lastName” has been deleted from the resultant object:
Method 3: Remove/Eliminate a Property From a JavaScript Object Using Spread Operator
Another approach to remove a property from a JavaScript object is to use the “spread operator”. It copies all of the properties except the specified property that has been deleted from the object.
Syntax
Use the following syntax to remove a property from a JavaScript object using spread operator:
Example
Create an object called “infoObject”:
name: 'John',
age: 30,
fieldOfInterest: "JavaScript"
};
Create a new object that does not contain the property “age”:
Print the new object called “restObj” on the console with the help of the “console.log()” method:
Output
That’s all about removing the property from a JavaScript object.
Conclusion
For removing or eliminating a property from a JavaScript object, utilize the “delete” operator, “filter()” method, or the “Spread operator (…)”. However, the “delete” operator is the easiest and most commonly used approach for removing the property from JavaScript objects. This post described several approaches for removing the property from the selected object.