如何以对象为成员循环遍历纯 JavaScript 对象

2022-01-29 00:00:00 loops javascript

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

How can I loop through all members in a JavaScript object, including values that are objects?

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

For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?

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

相关文章