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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read 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 👍

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay