How To: Delete property from an Object using spread operator
Calvin Torra
Posted on December 19, 2021
Everyday there’s something new to learn with Javascript.
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 it turns out 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
I now get the removed property value and also a new object with all the rest of the values.
💖 💪 🙅 🚩
Calvin Torra
Posted on December 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.