这是我的json数据
var data = [ {"unit":"a", "status":"Stopped / Idle", "val":21.2022222222222222}, {"unit":"a", "status":"Working", "val":53.3066666666666667}, {"unit":"a", "status":"Headland Turning", "val":0.04694444444444444444}, {"unit":"a", "status":"Transport", "val":5.1425000000000000}, {"unit":"b", "status":"Stopped / Idle", "val":334.7358333333333333}, {"unit":"b", "status":"Working", "val":212.6386111111111111}, {"unit":"b", "status":"Headland Turning", "val":26.2955555555555556}, {"unit":"b", "status":"Transport", "val":0.00444444444444444444} ];
unit 是类别
unit
我希望数据可以通过以下方式格式化,以便可以插入seriesHighCharts中的option:
series
series: [{ name: 'Stopped / Idle', data: [21.2022222222222222, 334.7358333333333333]}, { name: 'Working', data: [53.3066666666666667, 212.6386111111111111]}, { name: 'Headland Turning', data: [0.04694444444444444444, 26.2955555555555556]}, { name: 'Transport', data: [5.1425000000000000, 0.00444444444444444444]}] });
谢谢。
var data = [ {"unit":"a", "status":"Stopped / Idle", "val":21.2022222222222222}, {"unit":"a", "status":"Working", "val":53.3066666666666667}, {"unit":"a", "status":"Headland Turning", "val":0.04694444444444444444}, {"unit":"a", "status":"Transport", "val":5.1425000000000000}, {"unit":"b", "status":"Stopped / Idle", "val":334.7358333333333333}, {"unit":"b", "status":"Working", "val":212.6386111111111111}, {"unit":"b", "status":"Headland Turning", "val":26.2955555555555556}, {"unit":"b", "status":"Transport", "val":0.00444444444444444444} ]; var seriesData = []; var xCategories = []; var i, cat; for(i = 0; i < data.length; i++){ cat = 'Unit ' + data[i].unit; if(xCategories.indexOf(cat) === -1){ xCategories[xCategories.length] = cat; } } for(i = 0; i < data.length; i++){ if(seriesData){ var currSeries = seriesData.filter(function(seriesObject){ return seriesObject.name == data[i].status;}); if(currSeries.length === 0){ currSeries = seriesData[seriesData.length] = {name: data[i].status, data: []}; } else { currSeries = currSeries[0]; } var index = currSeries.data.length; currSeries.data[index] = data[i].val; } else { seriesData[0] = {name: data[i].status, data: [data[i].val]} } }
现在,你已经seriesData和xCategories你可以通过使用类似的东西实例图表
seriesData
xCategories
chart = new Highchart({chart: {renderTo: 'chart-div', type: 'column' }, plotOptions: {column: {stacking: 'normal'}}, xAxis:{ categories: xCategories}, series: seriesData });
编辑:这是jsFiddle:http : //jsfiddle.net/sujay/UMeGS/