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:
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;
JavaScriptor
delete object['property'];
JavaScriptThe 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'}
JavaScriptThe delete operation modifies the original object. Therefore it is a mutable operation.
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;
JavaScriptFor 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'}
JavaScriptIf we want to do this dynamically, we can do:
const name = 'propertyToBeRemoved';
const { [name]: removedProperty, ...remainingObject } = object;
JavaScriptFor example:
let blog = {name: 'Wisdom Geek', author: 'Saransh Kataria'};
const name = 'author';
const { [name]: removedProperty, ...remainingObject } = blog;
console.log(removedProperty); // Saransh Kataria
console.log(remainingObject); // {name: 'Wisdom Geek'}
JavaScriptIt 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!
I am terrible at optimizing my keyboard layout for anything. But off lately, my little…
I recently switched completely to the Brave browser and have set ad blocking to aggressive…
I was preparing a slide deck for a hackathon and decided to put in a…
I have been using npx a lot lately, especially whenever I want to use a…
Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…
While working on a project, I wanted to do an integrity check of a file…