Say we want to create a copy of an existing object, reusing most of the properties while dropping few. In order to remove unwanted properties, there are two basic patterns we usually follow.
Let say we have the following object to work with:
Let obj = {
Name:'Ahmed Murtaza',
Email:'ahmed_murtaza@xyz.com',
twitter:'ahmedgmurtaza',
fb:'ahmedgmurtaza'
};
Old school way
First approach is to use delete
operator, for that we first duplicate the original object and then explicitly delete the unwanted property out of it, here the unwanted property is twitter
:
Let obj2 = Object.assign({}, obj);
delete obj2.twitter;
🌟 Using Object destructuring + rest operator:
using this pattern, we isolate the removing property using destructuring format and name the rest of the properties as new object:
let { twitter, ...obj2 } = obj;
console.log(obj2); // obj2 does not carries twitter property
Using the above approach, we can immutably remove any property out of the object or can pick the one we need while ignoring the rest of the properties.
Top comments (2)
Your final code snippet has a typo. For example, node.js will give you the error: "ReferenceError: obj2 is not defined".
Instead try this:
let { twitter, ...obj2 } = obj;
Corrected now, thanks for identifying 👍