javascript - 在对象内循环 json 对象

标签 javascript jquery json

我知道这个问题已被问过一千次,但我一直无法找到有助于我构建 json 对象的方式的解决方案。可能是我的结构有误。

这是我的 json:

check_styles = {
    'html':{
        'background-color':'rgb(0, 0, 0)',
        'color':'rgb(0, 0, 0)'
    },
    '#my-div':{
        'background-color':'rgb(0, 0, 0)'
    }
};

我想循环并获取值 'html', 'background-color', 'rgb(0, 0, 0)' 然后是 'html', 'colour' , 'rgb(0, 0, 0)' 等发送到函数。

到目前为止,这是循环,但我无法在对象中获取对象的值。我不认为另一个循环是答案。

function style_check(styleList)
{

    for (var key in styleList) {
        if (styleList.hasOwnProperty(key) ){
            console.log( "key:"+key+", val:"+styleList[key] );
        }
    }

}

****我的解决方案

在 3 种不同的完全有效的解决方案之后,我选择了一个嵌套循环,因为我对 javascript 的了解有限,这对我来说很有意义。

function style_check(styleList)
{
    for (var selector in styleList) {
        if (styleList.hasOwnProperty(selector) ){
            for (var property in styleList[selector]) {
                if (styleList[selector].hasOwnProperty(property) ){
                    console.log( "selector:"+selector+", property:"+property+", value:"+styleList[selector][property] );
                }
            }
        }
    }
}

最佳答案

是的,嵌套循环就是答案。

function style_check(styleList)
{
    for (var key in styleList) {
        if (styleList.hasOwnProperty(key) ){
            console.log( "key:"+key+", val:"+styleList[key] );
            var obj = styleList[key];
            for (var objkey in obj){
                if (obj.hasOwnProperty(objkey)){
                    console.log("key2:"+objkey+",val:"+obj[objkey]);
                }
            }
        }
    }
}

检查这个fiddle

关于javascript - 在对象内循环 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36536484/

相关文章:

javascript - js对不同的div相同的onclick

javascript - 使用ajax将html内容附加到html

jquery - 执行 jQuery 悬停下拉菜单的正确方法(无故障)

javascript - 在页面加载时隐藏文档正文

json - 德尔福XE8 : Memory Leak with method datasnap server

php - 带有 json 响应的 Symfony 操作

javascript - 帐户密码电子邮件 token 是否会过期?

jquery - 移动浏览器中 $(window).scroll 事件的触发率

javascript - 是否可以使用 jQuery 搜索 json 结果

javascript - Wordpress 子主题 css 不会覆盖父 css