1

I want to do something like this. There is object like

obj = { a: "xxx", b: "xxx", c: "xxx", d: "xxx", e: "xxx", f: "xxx" }

There i want to remove the values of property c and d and to put them in array like arr = ["xxx" , "xxx"] . Then I want to add this array to the obj object as

obj = { a: "xxx", b: "xxx",  c: ["xxx", "xxx"], e: "xxx", f: "xxx" }

so is there way to this using ES6 spread and rest operators

How to do so if i have to remove values of n number(unknown it can be a 1 or 2 or 3 ..) properties and put them in array like above i have explained

5
  • Welcome to StackOverflow. Please read this how to ask Commented Mar 13, 2018 at 5:54
  • why 'f' was added to your new json obj? Commented Mar 13, 2018 at 5:56
  • @G_S I was there. Just on new line due to incorrect formatting. Commented Mar 13, 2018 at 6:00
  • If the properties and their number are unknown, you cannot use rest/spread syntax. Commented Mar 14, 2018 at 4:58
  • ... is not an operator, and object rest/spread properties is not part of ES6. It's coming with ES9 this year. Commented Mar 14, 2018 at 5:00

1 Answer 1

2

You could do it using destructuring and temporary consts.

const obj = {a:"xxx" , b:"xxx", c:"xxx" , d:"xxx" , e:"xxx", f:"xxx"}

const { c, d, ...rest} = obj; // pick props you want to remove and keep rest

// create a new object by spreading `rest` and adding new property
console.log({...rest, c: [c, d]});

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

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.