Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2015 Destructure object twice in same scope

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
}
like image 491
Matt K Avatar asked Dec 13 '15 15:12

Matt K


People also ask

Can you Destructure nested object?

Nested Object and Array Destructuring Here's another example with an array of objects: You can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .

Can you Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

Can you Destructure array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

What does it mean to Destructure an object JavaScript?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value.


1 Answers

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);
}
like image 141
dfreeman Avatar answered Oct 01 '22 03:10

dfreeman