for jq 嵌套,使用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?

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?

解决方案

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值