DEV Community

Cover image for ✨ How to Immutably remove property from JavaScript Object
Ahmed Murtaza
Ahmed Murtaza

Posted on • Edited on

✨ How to Immutably remove property from JavaScript Object

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'
};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

🌟 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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
steve_53b0d637d98a profile image
Steve Saxon • Edited

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;

Collapse
 
ahmedgmurtaza profile image
Ahmed Murtaza

Corrected now, thanks for identifying 👍