Sasi Kumar M
Sasi Kumar M

Reputation: 2630

Delete a property from JavaScript object without using delete operator

I need to extract certain properties from an object and assign to a new object. In a traditional way, I can assign manually whats required from an object property to a new object's property.

Currently i am using delete operator on the original object and creating a new object.

Is there a better way to do it.

Upvotes: 0

Views: 756

Answers (2)

Karthikeyan Mohan
Karthikeyan Mohan

Reputation: 118

Using ES6 Deconstructing Operator you can do a

ler arr = [{id:1, name: foo}, {id:2, name: bar}]
arr.map({id, ...item} => {
   return item
})

Consider you want to remove id property the above code will remove the id property and returns the object containing the name property.

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386540

You could destructure an object and pick the unwanted and get the rest as result object.

It uses

var object = { a: 1, b: 2, c: 3 },
    key = 'a',
    { [key]:_, ...result } = object;

console.log(result);

Upvotes: 4

Related Questions