0

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.

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer! Could you explain how [key]:_ works and what the idea behind it is called?
Thanks for the detailed explanations, much appreciated!
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.