Reputation: 4948
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
}
Upvotes: 11
Views: 2164
Reputation: 2834
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);
}
Upvotes: 17