-3

I have the following line with destructuring syntax;

const [
  {data: dataResponse},
  {data: stateDistrictWiseResponse},
  {data: statesDailyResponse},
  {data: stateTestResponse},
  {data: sourcesResponse},
  {data: zonesResponse},
] = someArr;

someArr is an array of objects (actually result of Promise.all([url1, url2,...], where each url returns a json object)

How is the above destructuring syntax evaluated?

adiga
  • 34,372
  • 9
  • 61
  • 83
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

0

The values extracted via destructuring syntax closely parallels the syntax of an object literal. For example, if someArr is defined as (or contains):

const someArr = [
        {data: 'dataResponse'},
        {data: 'stateDistrictWiseResponse'},
];

then the syntax

const [
        {data: dataResponse},
        {data: stateDistrictWiseResponse},
] = someArr;

will put the 'dataResponse' string into the dataResponse variable, and the 'stateDistrictWiseResponse' string into the stateDistrictWiseResponse variable.

The colon after the property indicates that the property is being extracted into a variable whose name is on the right of the colon. (If there is no colon when destructuring, the value is put into a new variable name which is the same as the property name, eg const { data } = someObj creates a variable named data which holds the value at someObj.data).

Your original code is quite hard to read though. I'd highly recommend mapping to create a new array of only the data properties first, then destructuring:

const dataArr = someArr.map(({ data }) => data);
const [
  dataResponse,
  stateDistrictWiseResponse,
  statesDailyResponse,
  stateTestResponse,
  sourcesResponse,
  zonesResponse,
] = dataArr;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks a lot...actually the "someArr" does not really have the structure as {data: 'dataResponse'} Instead it looks something like { "cases_time_series": [ { "a1": "1" } ], "statewise": [ { "a2": "2" } ], "tested": [ { "a3": "3" } ] } – copenndthagen May 17 '20 at 16:11
  • Then the code you posted in the question will not extract any properties, so they'll all be `undefined` – CertainPerformance May 17 '20 at 17:39
  • Actually I just had a quick followup....So you indicted the difference based on whether there is colon after the property or not. What I tried is without the colon; var [ {A}, {B}, ] = someArr; Now, I was expecting variables "A" & "B" to get/contain the values...But I see they are undefined after executing the above line of code... So, not sure if this is really destructuring syntax or something else is going on... – copenndthagen May 19 '20 at 05:18