JS HighCharts.js饼图数据格式不同

时间:2016-07-15 14:48:30

标签: javascript jquery highcharts

我正在使用Highcharts,我开始使用此代码获得一个可行的饼图:

//THE DATA:
var data = [{ name: 'Name 1', y: 20, id: 0 },{ name: 'Name 2', y: 10, id: 1 },{ name: 'Name 3', y: 10, id: 2 }];


//THE CHART CODE:
chart = new Highcharts.Chart({

   series:[
      {
         "data": data,
          type: 'pie',
          animation: false,
          point:{
              events:{
                  click: function (event) {
                      //alert(this.id);
                  }


              }
          }          
      }
   ],
   "chart":{
      "renderTo":"container"
   },
});

//The above with create a pie chart with 3 names

我的问题从下面开始,因为我已经获得了需要以不同格式阅读的数据

//The Data

var mydata =[{

    "001":{

        "name":"Name 1",
        "subhere":{
            "subhere1":2
        }

    },
    "002":{

        "name":"Name 2",
        "subhere":{
            "subhere1":20
        }

    },


}];

如何获取上面的数据以使用饼图?

1 个答案:

答案 0 :(得分:1)

我会重新格式化给你的数据,就像在Highchart中为你工作的data[]一样。

试试这个:

var data = [];
    for (var i = 0; i < mydata.length; i++) {       //looping through data received
        var obj = mydata[i];      //current obj in loop
        var newObj = {      //creating new obj with same structure as the 'data' that works
            name: obj.name,
            y: obj.subhere.subhere1,
            id: i       
        };

        data.push(newObj);      //pushing each object into the data array
    }

让我知道它是怎么回事!我希望它有所帮助,祝你好运!