This content originally appeared on DEV Community and was authored by Ahmed Murtaza
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 obj2 = { 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.
This content originally appeared on DEV Community and was authored by Ahmed Murtaza
Ahmed Murtaza | Sciencx (2021-08-25T17:48:40+00:00) ✨ How to Immutably remove property from JavaScript Object. Retrieved from https://www.scien.cx/2021/08/25/%e2%9c%a8-how-to-immutably-remove-property-from-javascript-object/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.