如何循环遍历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"
    }
}

当前回答

for (var key in validation_messages) {
    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if (!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}

其他回答

在ECMAScript 5下,可以组合Object.keys()和Array.protocol.forEach():

变量obj={第一个:“约翰”,上一个:“Doe”};////访问非继承的可枚举密钥//Object.keys(obj).forEach(函数(键){console.log(key,obj[key]);});

每个2

(在此处找到):

var lunch = {
    sandwich: 'ham',
    age: 48,
};
lunch.forEach2(function (item, key) {
    console.log(key);
    console.log(item);
});

代码:

if (!Object.prototype.forEach2) {
    Object.defineProperty(Object.prototype, 'forEach2', {
        value: function (callback, thisArg) {
            if (this == null) {
                throw new TypeError('Not an object');
            }
            thisArg = thisArg || window;
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    callback.call(thisArg, this[key], key, this);
                }
            }
        }
    });
}
for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}

有几种方法可以做到这一点。。。

1) 两层的。。。循环中。。。

for (let key in validation_messages) {
   const vmKeys = validation_messages[key];
   for (let vmKey in vmKeys) {
      console.log(vmKey + vmKeys[vmKey]);
   }
}

2) 使用Object.key

Object.keys(validation_messages).forEach(key => {
   const vmKeys = validation_messages[key];
   Object.keys(vmKeys).forEach(key => {
    console.log(vmKeys + vmKeys[key]);
   });
});

3) 递归函数

const recursiveObj = obj => {
  for(let key in obj){
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      console.log(key + obj[key]);
    } else {
      recursiveObj(obj[key]);
    }
  }
}

并将其称为:

recursiveObj(validation_messages);
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"