代码之家  ›  专栏  ›  技术社区  ›  hnacer

以适合Highcharts的格式制作JSON

  •  -1
  • hnacer  · 技术社区  · 6 年前

    以下是响应返回的JSON数据:

    [{“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”:“name”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 回复  |  直到 6 年前
        1
  •  0
  •   Martin Adámek    6 年前

    首先创建一个临时对象,在其中存储每个组 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);