简体   繁体   English

具有复杂嵌套的数组解构 object

[英]Array destructuring with complex nested object

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) someArr是一个对象数组(实际上是Promise.all([url1, url2,...]的结果,其中每个 url 返回一个 json 对象)

How is the above destructuring syntax evaluated?如何评估上述解构语法?

The values extracted via destructuring syntax closely parallels the syntax of an object literal.通过解构语法提取的值与 object 文字的语法非常相似。 For example, if someArr is defined as (or contains):例如,如果someArr定义为(或包含):

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.会将'dataResponse'字符串放入dataResponse变量,将'stateDistrictWiseResponse'字符串放入stateDistrictWiseResponse变量。

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 ). (如果解构时没有冒号,该值将被放入一个与属性名称相同的新变量名称中,例如const { data } = someObj创建一个名为data的变量,该变量将值保存在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:我强烈建议首先映射以创建仅包含data属性的新数组,然后解构:

const dataArr = someArr.map(({ data }) => data);
const [
  dataResponse,
  stateDistrictWiseResponse,
  statesDailyResponse,
  stateTestResponse,
  sourcesResponse,
  zonesResponse,
] = dataArr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM