使用jQuery循环遍历嵌套对象 [英] Loop through nested objects with jQuery
本文介绍了使用jQuery循环遍历嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿大家我正在尝试找到循环数组的最动态方法并返回特定值返回特定值... json结构很深,可能会改变,可能有$ .each()公式可以帮助?
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?
示例:
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
值,但instea d硬编码就像这样: myobj.obj2.key3.nest2
我用 $。每个()$有一种动态方式c $ c> mybe?
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?
推荐答案
您可以简单地将调用嵌套到 $。每个
:
You can simply nest calls to $.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);
}
}
如果你想知道自己有多深,那么你也可以这样做:
If you want to know how deep you are, you can do that too:
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;
}
这篇关于使用jQuery循环遍历嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文