Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 21, 2022 02:09 am GMT

How to Remove a Property from a JavaScript Object

There are two ways to remove a property from a JavaScript object: one is the mutable way of doing it by using the delete operator. And the second one is the immutable way of doing it by using object restructuring. Let us go through each of these:

1. The delete operator

delete is a JavaScript instruction that allows us to remove a property from a JavaScript object. There are a couple of ways to use it:

  • delete object.property;

  • delete object[property];

The operator deletes the corresponding property from the object.

let blog = {name: 'Wisdom Geek', author: 'Saransh Kataria'};const propToBeDeleted = 'author';delete blog[propToBeDeleted];console.log(blog); // {name: 'Wisdom Geek'}

The delete operation modifies the original object. Therefore it is a mutable operation.

2. Object destructuring

Using the object restructuring and rest syntax, we can destructure the object with the property to be removed and create a new copy of it. After the destructuring, a new copy of the object would be created and assigned to a new variable without the property that we chose to remove.

const { property, ...remainingObject } = object;

For example:

let blog = {name: 'Wisdom Geek', author: 'Saransh Kataria'};const { author, ...blogRest } = blog;console.log(blogRest) // {name: 'Wisdom Geek'};console.log(blog); // {name: 'Wisdom Geek', author: 'Saransh Kataria'}

If we want to do this dynamically, we can do this:

const name = 'propertToBeRemoved';const { [name]: removedProperty, ...remainingObject } = object;

It is also possible to remove multiple properties using the same syntax.

And those are the 2 ways to remove a property from a JavaScript object. If you have any questions, feel free to drop a comment below!

Originally published at https://www.wisdomgeek.com on August 29, 2021.


Original Link: https://dev.to/saranshk/how-to-remove-a-property-from-a-javascript-object-4gg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To