首页 > 解决方案 > 如何使用 JavaScript 访问 JSON 数据中嵌套数组中的特定元素?

问题描述

我有 JSON 数据,其结构如下。意图是查找特定的数据点,例如年利润,即 5000。

我想通过按名称查找列来做到这一点,例如“利润”,识别列索引(示例中为 3),然后使用列索引选择第二个节点中的第 n 个(3rd)元素(“annual” ) 的“数据”数组。

如何使用findIndex()Javascript 中的函数执行此操作(请参阅下面我的代码的关键部分)?

JSON数据:

{
  "datatable": {
    "data": [
      [
        "AAPL",
        "quarterly",
        1000,
        2000
      ],
      [
        "AAPL",
        "annual",
        5000,
        10000
      ]
    ],
    "columns": [{
        "name": "ticker"
        "type": "String"
      },
      {
        "name": "timedim"
        "type": "String"
      },
      {
        "name": "profit",
        "type": "Integer"
      },
      {
        "name": "revenue",
        "type": "Integer"
      }
    ]
  }
}

JavaScript 代码:

  // daten contains the "data" array of the JSON dataset
  // spalten contains the "columns" array of the JSON dataset
  
  var i = spalten.findIndex(obj => obj.name == "profit");
  output += '<p>Annual profit AAPL: ' + daten[i] + '</p>';
  elroot.innerHTML += output;

标签: javascriptarraysjsonobjectecmascript-6

解决方案


根据您提供的 JSON 结构,以下将起作用。如果您想根据参数获得特定的利润,编写一个函数会很好。

  var output = ""
  function getProfit(type="annual", column=2) {
    var arrForType = yourData.datatable.data.find(arr => arr.indexOf(type) !== -1);
    return arrForType[column];
  }

  var i = yourData.datatable.columns.findIndex(obj => obj.name == "profit");
  output += '<p>Annual profit AAPL: ' + getProfit("annual", i) + '</p>';
  document.body.innerHTML += output;


推荐阅读