Reputation: 1086
Making a simple bar chart. Every data that will be displayed has this structure:
var data = [{
"id": "myId",
"fillColor": "myColor"
},
{
"id": "myId2",
"fillColor": "myColor"
},
...]
Now, for each column that will be shown:
var columns = [{
"category": "My category", //what will be displayed as a label
"myId": 200 //a value to fill
},
{
"category": "Me second category",
"myId2": 300
},
...]
While displaying a simple bar, I just loop through the array, get the id from "data" and display the value from "columns".
for(var i = 0; i < columns.length; i++) {
id = data[i]["id"];
//display the value with
value = columns[i][id]; //and display it later
}
All this is working perfectly.
Now, I needed to do a stacked bar, so at first, I thought of adding the "id" from data to column with value, for example in the first column:
{
"category": "My category",
"myId": 200,
"myId2": 150
},{
"category": "My category2",
"myId2": 300
}
And here is where I get stuck. I don't know how to loop through key-values from objects with different numbers of pairs key-value. Javascript doesn't have a foreach()
function as can be PHP.
Hope this is more clarifying.
Upvotes: 0
Views: 261
Reputation: 8181
I don't know how to loop through key-values from objects with different numbers of pairs key-value. Javascript doesn't have a foreach() function as can be PHP.
So, Javascript does have a forEach
and below is how you loop thru to get key values from an object.
var myObj = [{
"key1": "value1",
"key2": "value2"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}];
myObj.forEach(function(val, index) {
for (var key in val) {
alert ("Array item: " + (index+1) + " Key: " + key + " Value: " + val[key]);
}
});
For all browsers including <=IE8
for (var i=0, j=myObj.length; i<j; i++) {
for (var key in myObj[i]) {
alert ("Array item: " + (i+1) + " Key: " + key + " Value: " + myObj[i][key]);
}
}
Upvotes: 1