代码之家  ›  专栏  ›  技术社区  ›  kosmicbird

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

  •  0
  • kosmicbird  · 技术社区  · 8 年前

    我正在做一个API调用,以从谷歌距离矩阵API返回数据,并将数据保存在我的(Read)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 是我所能做到的最深的一次。

    有人能帮忙吗?

    1 回复  |  直到 8 年前
        1
  •  0
  •   pipereset    8 年前

    我尝试了(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] 如果其中一个数组为空,将引发错误。有些库在这种情况下会优雅地失败: