0

is there a 1-step way to destructure object into 2 objects using some defined set of props.

For example, having initial object

const obj = {
prop1: "Prop1",
prop2: "Prop2",
prop3: "Prop3",
....
}

i'd like to do smth like:

const { firstObj: { prop1, prop2, prop3 }, secondObj: { ...rest }} = obj;

So far I have to do it in 2 steps like here Destructure to two separate variables:

  1. destructure obj prop1, prop2, prop3 and ...rest
  2. save {prop1, prop2, prop3 } as firstObj, {...rest} as secondObj
Ross
  • 1,641
  • 3
  • 15
  • 16
  • `ecmascript-2020`: _"Only use this tag where the question specifically relates to new features or technical changes provided in ECMAScript 2020."_ - Destructuring is part of ECMAScript 2015 – Andreas Oct 08 '22 at 10:41

1 Answers1

2

You could destructure and take a new object with default values.

Even it is working, it is better to use separate assignments for firstObj.

const
    obj = { prop1: "Prop1", prop2: "Prop2", prop3: "Prop3", prop4: "Prop4", prop5: "Prop5" },
    { prop1, prop2, prop3, firstObj = { prop1, prop2, prop3 }, ...secondObj } = obj;

console.log(firstObj);
console.log(secondObj);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392