11

Is there a clean way to destructure the same variables from 2 similar objects in the same scope?

function(oldState, newState) {
  let {foo, bar} = oldState;
  // do stuff //
  let {foo, bar} = newState; // illegal double declaration in same scope
  {foo, bar} = newState; // illegal, not sure why
  let {foo: foo1, bar: bar1} = newState; // legal but ugly
  foo = newState.foo; // legal, but requires multiple lines
}
Matt K
  • 4,813
  • 4
  • 22
  • 35

1 Answers1

17

You can wrap the assignment in parens to reassign the variables via destructuring. The reason this is necessary is because otherwise the { is assumed by the parser to begin a block rather than an object literal or assignment pattern. This blog post explains the situation in more detail.

function(oldState, newState) {
  let {foo, bar} = oldState;
  // do stuff //
  ({foo, bar} = newState);
}
dfreeman
  • 2,834
  • 2
  • 20
  • 24
  • 1
    Not that the `{...}` here do not denote an object literal either. – Felix Kling Dec 13 '15 at 17:36
  • 1
    True, it's technically an `ObjectAssignmentPattern`, but the point remains that you're gonna have a bad time with anything in statement position that has a leading curly and isn't a block statement :) – dfreeman Dec 13 '15 at 21:52