Reputation: 2630
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
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
Reputation: 386540
You could destructure an object and pick the unwanted and get the rest as result object.
It uses
{ [key]:_, ...result } = object;
^^^^^
destructuring assignment with an
{ [key]:_, ...result } = object;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Assigning to new variable names (which is not used anymore) and
{ [key]:_, ...result } = object;
^
{ [key]:_, ...result } = object;
^^^
var object = { a: 1, b: 2, c: 3 },
key = 'a',
{ [key]:_, ...result } = object;
console.log(result);
Upvotes: 4