5

大家好,我正在尝试寻找最动态的方式来循环遍历数组并返回特定值返回特定值...... 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 来做这件事?

4

1 回答 1

19

您可以简单地嵌套调用$.each

实例| 直播源

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

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

实例| 直播源

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;
}
于 2013-07-09T11:14:31.533 回答