如何循环使用对象作为成员的普通 JavaScript 对象 [英] How to loop through a plain JavaScript object with the objects as members

查看:29
本文介绍了如何循环使用对象作为成员的普通 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]);
    }
}

这篇关于如何循环使用对象作为成员的普通 JavaScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆