2

Suppose I have two objects containing the same keys but different values and I use a destructuring assignment on the first one:

const obj1 = {a:1, b:2, c:3}
const obj2 = {a:4, b:5, c:6}
let {a, b, c} = obj1

If later (say depending on some condition like the values are falsey) I was to reassign a, b and c, I find I have to do so like:

a = obj2.a
b = obj2.b
c = obj2.c

Since both the following give a SyntaxError:

{a, b, c} = obj2
let {a, b, c} = obj2

Is it possible to reassign these variables using the same syntax as used initially (using a one-liner rather than reassigning each variable inividually)? If so then how can I do this?

pjdavis
  • 325
  • 4
  • 25
  • Thanks for the link since it explains that the accepted answer. i.e. that the parentheses `( ... )` around the assignment statement are required here, since the `{...}` operators having multiple meanings in JavaScript – pjdavis Sep 14 '19 at 22:07

1 Answers1

3

You can surround the first option with parenthesis: ({a, b, c} = obj2);

const obj1 = {a:1, b:2, c:3}
const obj2 = {a:4, b:5, c:6}
let {a, b, c} = obj1;

console.log(a);

({a, b, c} = obj2);

console.log(a);
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80