动态创建Json数组Javascript

时间:2015-07-15 02:34:41

标签: javascript jquery chart.js

我正在使用Chart.js并且为了生成图表,加载的数据似乎是Json格式。例如

var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
    {
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 55, 40]
    },
    {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: [28, 48, 40, 19, 86, 27, 90]
    }
]};

我试图通过使用来自Json响应的数据来创建类似于上面示例的变量... Json响应格式为:

{
"points": {
"0": {
  "data_in": 8606441,
  "data_out": 25531384,
  "num_request": 2712,
  "time": "Fri, 10 Jul 2015 00:00:00 GMT"
},
 "1": {
  "data_in": 1719403,
  "data_out": 3463972,
  "num_request": 1446,
  "time": "Fri, 10 Jul 2015 01:00:00 GMT"
 },
 "2": {
  "data_in": 284120,
  "data_out": 3244090,
  "num_request": 786,
   "time": "Fri, 10 Jul 2015 02:00:00 GMT"
 },

我正在尝试填充一个名为temp的变量来匹配Chart.js格式。

   var temp = {
   labels: [],
   dataset: [
    {
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: []
  }
  ]
 };



    $.getJSON('/api/time_points', data, function(data){
    $.each(data.points, function( index, value ){
        temp.labels.push(data.points[index].time);
        temp.dataset[data].push(data.points[index].num_request);
    });

});

但这似乎并不奏效。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

temp.dataset是一个数组,您正在尝试将数据(一个对象)用作索引。

应该是这样的:

temp.dataset[0].push(data.points[index].num_request);

(或索引应该是什么)不是:

temp.dataset[data].push(data.points[index].num_request);