You often need to remove some keys from an object in Javascript. Here are the two simple ways to delete a key from an object in JavaScript.
Removing a key from an object with the delete operator
You can use the delete operator to remove a key from an object in JavaScript. You just have to mention the key with the delete operator. Check the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const Employee = { firstname: 'John', lastname: 'Doe', post: "developer", }; console.log(Employee.firstname); // John delete Employee.firstname; console.log(Employee.firstname); // undefined |
The output of the above code will be:
“John”
undefined
You can also use the other syntax with the delete operator. See the example given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const Employee = { firstname: 'John', lastname: 'Doe', post: "developer", }; console.log(Employee.firstname); // john delete Employee["firstname"]; console.log(Employee.firstname); // undefined |
The above code will do the same thing and the output will be the same as above.
Using undefined to remove a key from an object
You can also set the key of an object to undefined which will also remove the key from that object. Check the example.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const Employee = { firstname: 'John', lastname: 'Doe', post: "developer", }; console.log(Employee.firstname); // <em>John </em> Employee["firstname"] = undefined; console.log(Employee.firstname) // <em>undefined</em> |
output:
“John”
undefined
Using the other syntax for removing the key from the object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const Employee = { firstname: 'John', lastname: 'Doe', post: "developer", }; console.log(Employee.firstname); Employee.firstname = undefined; console.log(Employee.firstname); |
The output will be the same as above. This second method also deletes a key from an object.
How to delete a key from a nested object in JavaScript?
You can use the delete operator or set the value to undefined to a nested object too. Here is an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const Employee = { firstname: 'John', lastname: 'Doe', post: "developer", contactInformation: { phone : 97134567891, email : "john123@gmail.com" } }; console.log(Employee.contactInformation.phone); // 97134567891 Employee.contactInformation.phone = undefined; console.log(Employee.contactInformation.phone); // undefined |
The above code will generate the following output.
97134567891
undefined
You can look into the delete operator in detail in mozila developer guide.
Conclusion
You can use the delete operator to remove a key from an object or use the other method which sets the key to undefined. Both these methods remove a key from an object in JavaScript.
Here is a way to remove a key from an object without mutating the original object.