DEV Community

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

Posted on • Edited on

2

✨ 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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

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 👍

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free