43
Deleting a property from a Javascript Object without Mutation
Hey everyone 👋🏻,
There are multiple approaches to do the same operation in Javascript. Every approach has its own pro’s and con’s and there is always better way to do a particular operation in Javascript. In this article, let us see how to properly delete a property in Javascript without mutating an object.
We end up running into hard-to-debug and completely avoidable issues if we keep mutating objects in Javascript. The object might have correct value somewhere but will be different at other place and we would have no idea what changed what.
So it is highly recommended to perform CRUD operations on Javascript objects without mutating the objects. Take a look at this post to understand more about why it is recommended to avoid mutating Javascript objects.
Consider the below object,
const person = {
firstName: "Tony",
lastName: "Stark",
team: "avengers",
worth: "billions",
};
so if you want to delete a key from the person object then one way to do this is
delete person.worth;
console.log(person);
or
delete person['worth'];
console.log(person);
Although delete can be used to delete a property, you end up mutating the object which can cause undetectable bugs later on.
A better way to delete a property without mutating is by using spread operator.
const {worth, …newPerson} = person;
console.log(newPerson);
Instead of mutating the original object, you create a new object and use it instead. If your object is a nested one then you may have to handle accordingly as using spread operator doesn’t perform a deep clone.
Want to delete an object from an Array without mutating the Array?
const people = [
{ id: 1, name: 'ninja' },
{ id: 2, name: 'darkknight' },
{ id: 3, name: 'dexter' }
...
];
const updatedPeople = people.filter(person => person.id !== 2);
console.log(updatedPeople);
// [
// { id: 1, name: 'ninja' },
// { id: 3, name: 'dexter' }
// ...
// ];
The updatedPeoplewill no longer have the person object with id 2.
Are there any other alternative and better approaches that you follow in your code? Share it with me in the comments.
43