Remove a key or property from Object in Javascript
To remove a property or key-value pair from an object using Javascript, you can use the delete keyword. You will need to pass the key name that you want to delete.
// Define an object
const employee = {
"name": "John Deo",
"department": "IT",
"project": "Inventory Manager"
};
// Remove a property
delete employee["project"];
console.log(employee);
Output
{
"name": "John Deo",
"department": "IT"
}
Live demo of the above code example
Method 1: Using delete keyword
As defined in the above code example we can use the delete keyword to remove a property from an object created using Javascript. We need to put the delete keyword before the object name along with the key that you want to remove.
Syntax
delete Object["key_name"]
Code Example
const subject = {
"name": "Math",
"score": 90,
"code": "M01"
};
delete subject["name"];
console.log(subject);
Output
{
"score": 90,
"code": "M01"
}
In the above code example, we have created an object 'subject' that contains three keys - name, score, and code. We want to remove the 'score' key from the object. For that, we are using the below code.
delete subject["name"];
Method 2: Remove key-value using destructuring
If you want to create a new object that will not contain the property that you want to remove, then you can use destructuring. You can use it if you are using ES6.
Code Example
const subject = {
"name": "Math",
"score": 90,
"code": "M01"
};
const { name, ...new_subject } = subject;
console.log(new_subject);
Output
{
"score": 90,
"code": "M01"
}
The Conclusion
These are the methods that can be used to delete a property from a Javascript object. If you have better code ways to do that, you can always contribute here by clicking on the following button. If you have any questions or queries, you can always post a comment on this page.
- Convert object {key: value} to Array [[key, value]] Javascript
- Filter an Array using object key value in Javascript
- Lodash - Convert paired Array to key value paired object
- Remove an object from array by value in Javascript
- Remove duplicates ids from object array
- Sort array of objects by key value in Javascript
- Loop through object javascript