簡體   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