简体   繁体   English

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

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

I'm making an API call to return data from the Google Distance Matrix API and saving that data in my (react)redux store. 我正在进行API调用以从Google Distance Matrix API返回数据,并将该数据保存在我的(react)redux存储中。

The data object being returned is structured like this: 返回的数据对象的结构如下:

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",
}

That data structure is returned when I console.log(this.props.matrixData) . 当我console.log(this.props.matrixData)时,将返回该数据结构。

I need to access distance.text & duration.text so that I can display them on a component screen. 我需要访问distance.text和duration.text,以便可以在组件屏幕上显示它们。

I made several different failed attempts like 我做了几次不同的失败尝试,例如

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

and

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

etc to access deeper, but this.props.matrixData.rows is the deepest I've been able to get without throwing an error. 等访问更深的内容,但是this.props.matrixData.rows是我所能获取的最深的信息,而不会抛出错误。

Can someone help please? 有人可以帮忙吗?

I tried your example in the (Chrome) browser console, but I left out the "type annotations". 我在(Chrome)浏览器控制台中尝试了您的示例,但省略了“类型注释”。 Your second example for access works for me, I am not sure why it would fail. 您的第二个访问示例对我有用,我不确定为什么会失败。

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" }"

Please note that o.rows[0].elements[0] will throw an error if one of the Arrays is empty. 请注意,如果其中一个数组为空,则o.rows[0].elements[0]将引发错误。 There are libraries which fail gracefully in such cases: 在以下情况下,某些库会正常失败:

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

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