遍历以数组为值的 Javascript 对象

loop through Javascript object that has an array as a value

我的对象看起来像这样

{
  "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"
  ]
}

您错误地遍历了第二个结构。它是一个数组,不是一个对象。

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