为Highcharts

时间:2018-05-11 23:45:06

标签: javascript jquery json highcharts

以下是Response返回的JSON数据:

  

[{" id":1," name":" AAA"," value":5},{&#34 ; id":1," name":" BBB"," value":8},{" id":1, " name":" CCC"," value":9},{" id":1," name" :" AAA","价值":15},{" id":1,"名称":" BBB&#34 ;,"价值":3},{" id":1,"名称":" CCC","价值&# 34;:5},{" id":1," name":" AAA"," value":3} ,, { " id":1," name":" BBB"," value":10},{" id" :1,"名称":" CCC""值":11}]

请问如何使用jquery或javascript获取正确的格式来绘制图表(Highcharts),如下所示:

series: [{
    name: 'AAA',
    data: [5, 15, 3]

}, {
    name: 'BBB',
    data: [8, 3, 10]

}, {
    name: 'CCC',
    data: 9, 5, 11]

}]

1 个答案:

答案 0 :(得分:0)

首先创建一个临时对象,按name存储每个组,然后通过map()将该对象转换为数组:



const data = [{"id":1,"name":"AAA","value":5}, {"id":1,"name":"BBB","value":8}, {"id":1,"name":"CCC","value":9}, {"id":1,"name":"AAA","value":15}, {"id":1,"name":"BBB","value":3}, {"id":1,"name":"CCC","value":5}, {"id":1,"name":"AAA","value":3}, , {"id":1,"name":"BBB","value":10}, {"id":1,"name":"CCC","value":11}];

const temp = {};
data.forEach(row => {
  if (!temp[row.name]) {
    temp[row.name] = { name: row.name, data: [] };
  }
  
  temp[row.name].data.push(row.value);
});

const series = {
  series: Object.keys(temp).map(name => ({ name, data: temp[name].data })),
};

console.log(series);