简体   繁体   English

使用jQuery循环遍历嵌套对象

[英]Loop through nested objects with jQuery

Hey everyone I am trying t find the most dynamic way to loop through an array and return specific values return specific values... The json is deeply structured and may change, could there be a $.each() formula that can help? 嘿大家我正在尝试找到循环数组最有活力的方法并返回特定值返回特定值... json结构深刻且可能会更改,是否有可以帮助的$ .each()公式?

Example: 例:

var myobj = {
    obj1: { key1: 'val1', key2: 'val2' },
    obj2: { key1: '2val1', 
           key2: { nest1: 'val1', nest2: 'val2', nest3: 'val3' }, 
           key3: { nest1: 'K3val1', nest2: 'K3val2', 
                 nest3: [
                         { nest1: 'val1', nest2: 'val2', nest3: 'val3' }, 
                         { nest1: 'val1', nest2: 'val2', nest3: 'val3' }
                        ]
                 }
          },
    obj3: { key1: 'dddddval1', key2: 'val2' }
    }

now lets say i want to retrieve " K3val2 " value but instead of hardcoding it like so: myobj.obj2.key3.nest2 is there a dynamic way I do this with $.each() mybe? 现在让我说我想要检索“ K3val2 ”值,而不是像这样硬编码: myobj.obj2.key3.nest2有一个动态的方式我用$.each() mybe做这个吗?

You can simply nest calls to $.each : 您可以简单地将调用嵌套到$.each

Live Example | 实例 | Live Source 直播源

// Loop the top level
$.each(myobj, walker);

function walker(key, value) {
    // ...do what you like with `key` and `value`

    if (value !== null && typeof value === "object") {
        // Recurse into children
        $.each(value, walker);
    }
}

If you want to know how deep you are, you can do that too: 如果你想知道自己有多深,你也可以这样做:

Live Example | 实例 | Live Source 直播源

var path = "";

// Loop the top level
$.each(myobj, walker);

function walker(key, value) {
    var savepath = path;

    path = path ? (path + "." + key) : key;

    // ...do what you like with `key` and `value`

    if (value !== null && typeof value === "object") {
        // Recurse into children
        $.each(value, walker);
    }

    path = savepath;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM