将json数组格式化为图表输入

时间:2016-03-08 10:52:43

标签: javascript jquery arrays json charts

嗨我得到json数组作为ajax请求的响应:

{"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05"
:0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}

现在我想通过将这些值提供给图表输入来准备图表,如下所示:(我想从上面的数组输出这样的颜色)

                              data: [{
                                    y: '2016-03-07',
                                    a: 100
                                    }, {
                                        y: '2016-03-08',
                                        a: 75
                                    }, {
                                        y: '2016-03-06',
                                        a: 50
                                    }, {
                                        y: '2016-03-05',
                                        a: 75
                                    }, {
                                        y: '2016-03-09',
                                        a: 50
                                    }, {
                                        y: '2016-03-03',
                                        a: 75
                                    }, {
                                        y: '2016-03-02',
                                        a: 180
                                    }
                                ],

我试过了:

var chart_params = {};
for (var key in data_chart) {
     let value = data_chart[key];
     chart_params = '{ y:'+ key+ ', a: '+value+' }';
}
console.log(chart_params);

但它没有按预期提供输出

2 个答案:

答案 0 :(得分:1)

试试这个

data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05" :0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}

var chart_params = [];
data_chart = data.chart;
 for (var key in data_chart) {
      var value = data_chart[key];
      chart_params.push({ y: key, a:value});
}
 console.log(chart_params);

jsfiddle:https://jsfiddle.net/hb8qd1p8/1/

答案 1 :(得分:1)

@ madalin 答案是您问题的正确解决方法,但要完成您想要的其他选项是使用map: -



var data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05":0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}};

var array = Object.keys(data.chart).map(function (key) {
  return { y: key, a: data.chart[key] }; 
});

document.write(JSON.stringify(array, null, 4));