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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const Employee = { firstname: 'John', lastname: 'Doe', age:22, }; const {age, ...newEmployee} = Employee; console.log(newEmployee); // output: Object { firstname: "John", lastname: "Doe" } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const removeKey = (obj, prop) => { let res = Object.assign({}, obj) delete res[prop] return res } const Employee = { firstName : "John", lastName : "Doe", age : 22, } const newEmployee = removeKey(Employee, "age"); console.log(newEmployee) // output : Object { firstName: "John", lastName: "Doe" } |
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.