首页 > 解决方案 > 如何在不知道键的情况下使用 javascript/jquery 从多维 json 数组中检索值?

问题描述

我有一个包含多维数组的 json 文件。第一层是城市,第二层是温度数据。我无法动态地从第二级提取值。

我尝试了以下方法:

console.log(Object.values(json[0])[3][1]) but it gives me errors.

不过,这很好用:

console.log(Object.values(json[0])[3])

下面是我的 JSON 代码示例:

[
  {
    "id": 1,
    "city": "Amsterdam",
    "country": "Netherlands",
    "monthlyAvg": [
      {
        "high": 7,
        "low": 3,
        "dryDays": 19,
        "snowDays": 4,
        "rainfall": 68
      },
      {
        "high": 6,
        "low": 3,
        "dryDays": 13,
        "snowDays": 2,
        "rainfall": 47
      },
      {
        "high": 10,
        "low": 6,
        "dryDays": 16,
        "snowDays": 1,
        "rainfall": 65
      },
      {
        "high": 11,
        "low": 7,
        "dryDays": 12,
        "snowDays": 0,
        "rainfall": 52
      },
      {
        "high": 16,
        "low": 11,
        "dryDays": 15,
        "snowDays": 0,
        "rainfall": 59
      },
      {
        "high": 17,
        "low": 11,
        "dryDays": 14,
        "snowDays": 0,
        "rainfall": 70
      },
      {
        "high": 20,
        "low": 12,
        "dryDays": 14,
        "snowDays": 0,
        "rainfall": 74
      },
      {
        "high": 20,
        "low": 12,
        "dryDays": 15,
        "snowDays": 0,
        "rainfall": 69
      },
      {
        "high": 17,
        "low": 10,
        "dryDays": 14,
        "snowDays": 0,
        "rainfall": 64
      },
      {
        "high": 14,
        "low": 9,
        "dryDays": 16,
        "snowDays": 0,
        "rainfall": 70
      },
      {
        "high": 9,
        "low": 6,
        "dryDays": 20,
        "snowDays": 1,
        "rainfall": 82
      },
      {
        "high": 7,
        "low": 1,
        "dryDays": 19,
        "snowDays": 1,
        "rainfall": 85
      }
    ]
  },
  {
    "id": 2,
    "city": "Athens",
    "country": "Greece",
    "monthlyAvg": [

我希望能够检索对应于高的值 7。我目前可以这样说:

json[0].monthlyAvg[0].high

如何在不指定“.high”的情况下获得结果

例如,这就是我想象的代码的样子: 所以是这样的:

"high": 7 -> 我想通过输入 json[0].monthlyAvg[0][0] 之类的内容来获得 7

"low": 3 -> 我想通过输入类似 json[0].monthlyAvg[0][1] 的内容来获得 7

"dryDays": 19 -> 我想通过输入 json[0].monthlyAvg[0][2] 之类的内容来获得 7

"snowDays": 4 -> 我想通过输入 json[0].monthlyAvg[3][0] 之类的内容来获得 7

"rainfall": 68 -> 我想通过输入 json[0].monthlyAvg[0][4] 之类的内容来获得 7

标签: javascriptjqueryarraysjson

解决方案


我认为您以错误的方式解决问题,因为有更多方便的方式来迭代数组。看看这段代码,你可以在这里找到一个工作示例: https ://codesandbox.io/s/wonderful-grothendieck-2rjze

jsonData.forEach(cityObject => {
  console.log(
    `*** Printing data for ${cityObject.city}, ${cityObject.country} ***`
  );

  cityObject.monthlyAvg.forEach(avg => {
    let stringStat = "";

    for (const key in avg) {
      let value = avg[key];

      if (stringStat.length > 0) stringStat += ", ";

      stringStat += `${key}: ${value}`;
    }

    console.log(stringStat);
  });
});

推荐阅读