DEV Community

Cover image for How To: Delete property from an Object using spread operator
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

How To: Delete property from an Object using spread operator

Original Post and more Here

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)