Reputation: 90
Hi i am getting json array as response of ajax request:
{"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}}
Now i want to prepare a chart by giving these values to chart input as below: ( i want output like this from above array )
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
}
],
I have tried :
var chart_params = {};
for (var key in data_chart) {
let value = data_chart[key];
chart_params = '{ y:'+ key+ ', a: '+value+' }';
}
console.log(chart_params);
but it is not giving output as expected
Upvotes: 1
Views: 63
Reputation: 15154
@madalin's answer is the correct fix for your issue, though another option to accomplish what you want is to use 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));
Upvotes: 1
Reputation: 32354
Try this
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/
Upvotes: 1