简体   繁体   中英

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.

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) .

I need to access distance.text & duration.text so that I can display them on a component screen.

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.

Can someone help please?

I tried your example in the (Chrome) browser console, but I left out the "type annotations". 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. There are libraries which fail gracefully in such cases:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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