繁体   English   中英

如何访问嵌套在多个对象和数组中的元素的值?

[英]How can I access the value of elements nested deeply within several objects and arrays?

我正在进行API调用以从Google Distance Matrix API返回数据,并将该数据保存在我的(react)redux存储中。

返回的数据对象的结构如下:

Object {
  "destination_addresses": Array [
    "21 Foo St, SomeCity, SomeState 33333, USA",
  ],
  "origin_addresses": Array [
    "5555 Somewhere Dr, Somewhere, Somewhere 55555, USA",
  ],
  "rows": Array [
    Object {
      "elements": Array [
        Object {
          "distance": Object {
            "text": "2,302 mi",
            "value": 3703935,
          },
          "duration": Object {
            "text": "1 day 10 hours",
            "value": 123162,
          },
          "status": "OK",
         },
      ],
    },
  ],
  "status": "OK",
}

当我console.log(this.props.matrixData)时,将返回该数据结构。

我需要访问distance.text和duration.text,以便可以在组件屏幕上显示它们。

我做了几次不同的失败尝试,例如

this.props.matrixData.rows.elements.distance.text 

this.props.matrixData.rows[0].elements[0]

等访问更深的内容,但是this.props.matrixData.rows是我所能获取的最深的信息,而不会抛出错误。

有人可以帮忙吗?

我在(Chrome)浏览器控制台中尝试了您的示例,但省略了“类型注释”。 您的第二个访问示例对我有用,我不确定为什么会失败。

var o = {
"destination_addresses": [
    "21 Foo St, SomeCity, SomeState 33333, USA",
],
"origin_addresses": [
    "5555 Somewhere Dr, Somewhere, Somewhere 55555, USA",
],
"rows": [
    {
    "elements": [
        {
        "distance": {
            "text": "2,302 mi",
            "value": 3703935,
        },
        "duration": {
            "text": "1 day 10 hours",
            "value": 123162,
        },
        "status": "OK",
        },
    ],
    },
],
"status": "OK",
};
o.rows[0].elements[0]; // logs "Object { distance: {…}, duration: {…}, status: "OK" }"

请注意,如果其中一个数组为空,则o.rows[0].elements[0]将引发错误。 在以下情况下,某些库会正常失败:

暂无
暂无

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

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