blog
contact
hire me

How To: Delete property from an Object using spread operator

IdontKnowJS

I was trying to manipulate an object and remove one of the properties but I didn’t want to mutate the original object. I knew there must be a cleaner way than to use the delete operator.

That got me thinking about the spread operator and I remembered you can remove properties while spreading the rest of the values into a new object.

let user = {
  name: "Calvin",
  age: 200,
  country: "Spain",
  food: "Pizza",
};
const { name, ...restOfUser } = user;
console.log(restOfUser);
console.log(name);

// { age: 200, country: 'Spain', food: 'Pizza' }
// Calvin

We now get the removed property value and also a new object with all the rest of the values.