如何循环遍历JavaScript对象中的所有成员,包括作为对象的值?

例如,我如何循环(分别访问“your_name”和“your_message”)?

var validation_messages = {
    "key_1": {
        "your_name": "jimmy",
        "your_msg": "hello world"
    },
    "key_2": {
        "your_name": "billy",
        "your_msg": "foo equals bar"
    }
}

当前回答

我认为值得指出的是,jQuery使用$.each()很好地解决了这个问题。

请参见:.each()

例子:

$('.foo').each(function() {
    console.log($(this));
});

$(this)是对象内的单个项目。如果不想使用jQuery的选择器引擎,请将$('.foo')转换为变量。

其他回答

for(var key in validation_messages){
    for(var subkey in validation_messages[key]){
        //code here
        //subkey being value, key being 'yourname' / 'yourmsg'
    }
}
for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}

这个问题

for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

就是您还将循环遍历原始对象的原型。

有了这个,你可以避免:

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)) {
            alert(prop + " = " + obj[prop]);
         }
      }
   }
}

我认为值得指出的是,jQuery使用$.each()很好地解决了这个问题。

请参见:.each()

例子:

$('.foo').each(function() {
    console.log($(this));
});

$(this)是对象内的单个项目。如果不想使用jQuery的选择器引擎,请将$('.foo')转换为变量。

var validation_messages = {
    "key_1": {
        "your_name": "jimmy",
        "your_msg": "hello world"
    },
    "key_2": {
        "your_name": "billy",
        "your_msg": "foo equals bar"
    }
}
for (var i in validation_messages) {
    console.log("i = \"" + i + "\"");
    console.log("validation_messages[\"" + i + "\"] = ");
    console.log(validation_messages[i]);
    console.log("\n");
    for (var j in validation_messages[i]) {
        console.log("j = \"" + j + "\"");
        console.log("validation_messages[\"" + i + "\"][\"" + j + "\"] = \"" + validation_messages[i][j] + "\"");
        console.log("\n");
    }
    console.log('\n');
}

输出:

i = "key_1"
validation_messages["key_1"] = 
{
  your_name:"jimmy",
  your_msg:"hello world"
}

j = "your_name"
validation_messages["key_1"]["your_name"] = "jimmy"

j = "your_msg"
validation_messages["key_1"]["your_msg"] = "hello world"


i = "key_2"
validation_messages["key_2"] = 
{
  your_name:"billy",
  your_msg:"foo equals bar"
}

j = "your_name"
validation_messages["key_2"]["your_name"] = "billy"

j = "your_msg"
validation_messages["key_2"]["your_msg"] = "foo equals bar"