Afshin Ghazi
Afshin Ghazi

Reputation: 2990

ES6 destructuring not returning correct result

I an trying to destructure two object with the same property names but only the names of the first set are observed.

let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)

and

  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)

But test1 is undefined

Upvotes: 0

Views: 71

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386883

If you have more objects with the same structure, you could take a function which returns an array of wanted properties.

const getProps = ({ a, b }) => [a, b];

let [a, b] = getProps(myObject1),
    [c, d] = getProps(myObject2);

Upvotes: 0

adz5A
adz5A

Reputation: 2032

let { a: a1, b: b1 }  = myObject1;
let { a: a2, b: b2 } = myObject2;

Will create variables a1, b1, a2, b2 from your 2 objects.

Upvotes: 1

balmukund kumar
balmukund kumar

Reputation: 149

Assign name to variables.

let a, b,
 ({ a,b } = myObject1);
({ a: A,b:B } = myObject2);

Upvotes: 1

Related Questions