如何以Json格式为highcharts创建数据

时间:2017-07-07 09:22:25

标签: javascript jquery json highcharts

我通过ajax获得了低于结果的结果,而我在ajax成功中得到的数据是

[{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}]

我正在尝试将此数据转换为格式

[{
  name: 'MCW',
  data: [6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000
]},{
  name: 'SJCPL',  
  data: [4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385]
}]

我正在尝试将此格式转换为https://jsfiddle.net/mcj075jf/

生成高级图表

如何使用for循环或$.each在jQuery中转换为上述格式。请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以按如下方式使用map



var plants = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var formattedData = plants.map((plant) => ({
  name: plant.plant_name,
  data: plant.employees_data.split(',').map((data) => parseFloat(data))
}));

console.log(formattedData);




答案 1 :(得分:0)

您可以使用解决方案https://jsfiddle.net/z10jheo2/

var data = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var newData = [];

for(var i=0; i<data.length; i++) {
   var tempData = {};
   tempData.name = data[i].plant_name;
   tempData.data = data[i].employees_data.split(',');
   newData.push(tempData); 
   console.log(newData);
}