2 Ways to Remove a key From Object Without Mutating

In JavaScript, if you remove a key from an object it will mutate the original object. Here are two simple ways to remove a key without mutating the object.

1. Use Object Destructuring

Modern JavaScript feature object destructuring can remove a key from an object. Check the example below.

This will create a newEmployee object and will not mutate the Employee object. Please note that this method will create another variable “age” which will be unused in the code.

2. Use a separate function to remove a key

You can write a separate function to remove a key from an object. Benefit of writing a separate function is reusability and there will not be any unused variables. Here is an example.

The above code will remove “age” from the object. By using this approach, you can remove any property dynamically from an object. This is reusable as you just have to pass the object and the property you want to remove.

If you want to read more about Object Destructuring check mozilla guide

Conclusion

You can use object destructuring or object.assign() method to remove a key from an object if you don’t want to mutate the original object.

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here