【问题标题】:How to access a specific element in nested array in JSON data using JavaScript?如何使用 JavaScript 访问 JSON 数据中嵌套数组中的特定元素?
【发布时间】:2019-02-25 00:24:53
【问题描述】:

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

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

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

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;

【问题讨论】:

    标签: javascript arrays json object ecmascript-6


    【解决方案1】:

    你有2-dimensional数组,所以,你需要两个索引:

    const 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"
          }
        ]
      }
    }
    var profitIndex = json.datatable.columns.findIndex(item => item.name == 'profit');
    var annualIndex = json.datatable.data.findIndex(array => array.indexOf('annual') > -1);
    var annualProfit = json.datatable.data[annualIndex][profitIndex];
    

    如果你需要一个函数,它可能如下所示:

    var getValueFromJson = function (json, columnName, dataMarker) {
        var columnIndex = json.datatable.columns.findIndex(item => item.name == columnName);
        var dataMarkerIndex = json.datatable.data.findIndex(array => array.indexOf(dataMarker) > -1);
        if (columnIndex < 0 || dataMarkerIndex < 0) {
            return null;
        }
        return json.datatable.data[dataMarkerIndex][columnIndex];
    }
    
    console.log(getValueFromJson(json, 'profit', 'quarterly'));
    console.log(getValueFromJson(json, 'profit', 'annual'));
    console.log(getValueFromJson(json, 'revenue', 'quarterly'));
    console.log(getValueFromJson(json, 'revenue', 'annual'));
    

    上面的代码打印:

    > 1000
    > 5000
    > 2000
    > 10000
    

    【讨论】:

      【解决方案2】:

      根据您提供的 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;
      
      

      【讨论】:

      • 函数应该稍微改一下,只去掉="annual"部分,改成type,对吧?所以它会很灵活,然后我也可以将它与“季度”一起使用。
      • 不需要,如果您不为该参数传递任何值,它是默认参数。因此,如果您通过例如 getProfit("quarterly", 3),它仍然可以工作。查看default parameters 获取信息。
      【解决方案3】:

      您不需要findIndex - 只需像这样使用findincludes

      const data = {
        "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"
            }
          ]
        }
      };
      
      function findValue(type) {
        return data.datatable.data.find(e => e.includes(type))[2];
      }
      
      console.log(findValue("annual"));
      console.log(findValue("quarterly"));

      【讨论】:

      • 谢谢。此解决方案在哪里选择“利润”列?
      • 它不选择列 - 它只是直接进入数字。
      • 嗨,杰克,谢谢。让我重新表述我的问题:如果我想灵活地在列名中搜索一个字符串,然后在 data 中返回相应的数据点,我需要在某处引用该字符串,不是吗?感谢您的澄清。
      【解决方案4】:

      这是基本思想,那么如果您显然需要扩展,则需要以更好的方式进行。

      let output = '';
      
      // Searches the desired index (refactor as needed)
      const index = spalten.findIndex(obj => obj.name == "profit")
      
      // Extract all the profits (if you dont need all just select the desired one)
      daten.map(item => output += `<p>${item[1]} profit ${item[0]}: ${item[index]}</p>`)
      

      【讨论】:

      • @Ignacia 第二行到底是做什么的,我如何在我的代码中实现它?谢谢。
      猜你喜欢
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多