Remove a property from an object
How to solve it
Approach 1
To to delete a property from an object in Javascript, we can use the delete operator. Consider the following object:
const obj = {x:1,y:2};
To remove property y we would call:
delete obj.y;
The modified object would now be:
{x:1}
When using the delete operator, you have to keep in mind that the operation will change/mutate the existing object. This is not always what we want to achieve. Sometimes we would want the original object to persist. The best way to achieve this is to create a new object. It should have all original properties but the one we want to have removed.
Approach 2
To avoid mutating the original object, we can use Object destructuring in combination with the Spread syntax. Consider again the following object:
const obj = {x:1,y:2};
Now we call:
const {y, ...newObj} = obj;
This will assign a new variable y with the value
obj.y
and create a new object with all the remaining properties of obj.