JS HighCharts.JS代码中出现Pie数据未定义错误

JS HighCharts.js Pie data undefined error in code

本文关键字:JS 数据 未定义 错误 Pie HighCharts 代码      更新时间:2023-09-26

我对以下代码有点问题:

//The Code:
    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
    }

//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
        }
    },

}];

控制台给我以下错误:

TypeError: obj.subhere is undefined y: obj.subhere.subhere1,

我可以看到subhere1名称实际上是存在的,所以理论上它不应该给我一个错误,对吧?。

如何解决此问题。。。有什么想法吗?

myData的格式看起来不正确。它在上一个括号后面有一个额外的逗号:

},

}];

您可以循环浏览您的对象属性:

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

要使用现有代码,可以将mydata的定义更改为:

var mydata =[
    {
        "name":"Name 1",
        "subhere":{
            "subhere1":2
        }
    },
    {
        "name":"Name 2",
        "subhere":{
            "subhere1":20
        }
    }

];