循环遍历具有数组作为值的Javascript对象

时间:2015-04-10 12:08:54

标签: javascript arrays object key

我的对象看起来像这样

{
  "about.php": [
    "#topNav",
    "#botNav",
    "#employees"
  ],
    "index.php": [
    "#blah"
  ]
}

我像这样循环播放

        var validation_messages = obj;

            for (var key in validation_messages) {
               if (validation_messages.hasOwnProperty(key)) {
                   var obj = validation_messages[key];
                    for (var prop in obj) {
                      if(obj.hasOwnProperty(prop)){
                        console.log(prop + " = " + obj[prop]);
                      }
                   }
                }
            }

我收到了这个结果

0 = #topNav
1 = #botNav
2 = #employees
0 = #blah

我需要对象键的名称,而不是对象值中数组的键。像这样:

about.php = #topNav
about.php = #botNav
about.php = #employees
index.php = #blah

如果它们不存在,我会将新值推送到数组中:

{
  "about.php": [
    "#topNav",
    "#botNav",
    "#employees"
  ],
    "index.php": [
    "#blah",
    "#newValue"
  ]
}

1 个答案:

答案 0 :(得分:1)

你错误地在第二个结构上循环。它是一个数组,而不是一个对象。

for (var key in validation_messages) {
    if (validation_messages.hasOwnProperty(key)) {
        var obj = validation_messages[key];

        // use a for loop here instead of for...in
        for (var i = 0, l = obj.length; i < l; i++) {
            console.log(key + " = " + obj[i]);
        }
    }
}

DEMO