JavaScript,循环不同键值对数的对象

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

制作一个简单的条形图。将要显示的每个数据都具有以下结构:

var data = [{
    "id": "myId",
    "fillColor": "myColor"
},
{
    "id": "myId2",
    "fillColor": "myColor"
},
...]

现在,对于将要显示的每一列:

var columns = [{
    "category": "My category", //what will be displayed as a label
    "myId": 200 //a value to fill
},
{
    "category": "Me second category",
    "myId2": 300
},
...]

在显示一个简单的条形图时,我只是循环遍历数组,从 "data" 获取 ID 并显示 "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
}

所有这些都运行良好。

现在,我需要做一个堆积条,所以一开始,我想到将数据中的 "id" 添加到有值的列中,例如在第一列中:

{
    "category": "My category",
    "myId": 200,
    "myId2": 150
},{
    "category": "My category2",
    "myId2": 300
}

这就是我卡住的地方。我不知道如何从具有不同数量的键值对的对象中循环键值。 Javascript 没有 foreach() 函数 PHP.

希望这更清楚。

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.

因此,Javascript 确实有一个 forEach,下面是您如何通过循环从对象中获取键值。

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

适用于所有浏览器,包括 <=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]);
    }
}