gafasmill gafasmill - 4 months ago 23
Javascript Question

JS HighCharts.js Pie data undefined error in code

I am having a bit of an issue with the following code:

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

},


}];


The console is giving me the following error:

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


I can see that the subhere.subhere1 names actually exists so in theory it should not be giving me an error, right?.

How can I fix this issue ... any ideas?

Answer

myData doesn't look correctly formatted. It has an extra comma after the bracket before last:

},

}];

You can loop through your object properties:

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
  }
}
Comments