如何仅在jsonObj数组中定位X或Y值

时间:2018-03-17 11:31:56

标签: javascript chart.js

我正在使用找到here的方法和chartJS来输入JSON响应中缺少的日期。

jsonObj["result"]["data"]从初始JSON响应中输出:

{
    "action": "data_link_day",
    "result": {
        "url_ending": "0",
        "data": [{
            "x": "2018-03-12",
            "y": 3
        }, {
            "x": "2018-03-16",
            "y": 5
        }]
    }
}

drawChart函数中,我需要将x / y值分别为graphData = y(数字)和labels = x(日期),方法是单独定位它们。我试图做jsonObj["result"]["data"].x,但显然不正确。

  function drawChart(jsonObj) {

      var graphData = jsonObj["result"]["data"],
          labels = jsonObj["result"]["data"];

      for (var i = 0; i < labels.length; i++) {
          //make sure we are not checking the last date in the labels array
          if (i + 1 < labels.length) {
              var date1 = moment(labels[i], "YYYY-MM-DD");
              var date2 = moment(labels[i + 1], "YYYY-MM-DD");


              //if the current date +1 is not the same as it's next neighbor we have to add in a new one
              if (!date1.add(1, "days").isSame(date2)) {

                  //add the label
                  labels.splice(i + 1, 0, date1.format("YYYY-MM-DD"));
                  //add the data
                  graphData.splice(i + 1, 0, 0);
              }
          }


      }
      ...
  }

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码将数据分成X和Y数组:

let data = jsonObj.result.data;
let dataX = data.map(data => data.x);
let dataY = data.map(data => data.y);

演示:

&#13;
&#13;
const json = `
{
    "action": "data_link_day",
    "result": {
        "url_ending": "0",
        "data": [{
            "x": "2018-03-12",
            "y": 3
        }, {
            "x": "2018-03-16",
            "y": 5
        }]
    }
}`;

const input = JSON.parse(json);

let data = input.result.data;
let dataX = data.map(data => data.x);
let dataY = data.map(data => data.y);

console.log(dataX);
console.log(dataY);
&#13;
&#13;
&#13;