使用jQuery循环遍历嵌套对象

时间:2013-07-09 11:11:21

标签: javascript jquery

嘿大家我正在尝试找到循环数组的最动态方法并返回特定值返回特定值... json结构很深,可能会改变,可能有$ .each()公式可以帮助

示例:

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' }
    }

现在假设我想要检索“K3val2”值,而不是像这样对其进行硬编码:myobj.obj2.key3.nest2我是否采用动态方式对$.each() mybe执行此操作?

1 个答案:

答案 0 :(得分:17)

您可以简单地将呼叫嵌套到$.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);
    }
}

如果你想知道自己有多深,你也可以这样做:

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