简体   繁体   中英

JavaScript, loop objects with different number of pairs key-value

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.

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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM