在嵌套数组深处按键查找 [英] Find by key deep in a nested array
本文介绍了在嵌套数组深处按键查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个对象:
[
{
'title': "some title"
'channel_id':'123we'
'options': [
{
'channel_id':'abc'
'image':'http://asdasd.com/all-inclusive-block-img.jpg'
'title':'All-Inclusive'
'options':[
{
'channel_id':'dsa2'
'title':'Some Recommends'
'options':[
{
'image':'http://www.asdasd.com' 'title':'Sandals'
'id':'1'
'content':{
...
我想找到一个id为1的对象.是否有类似这样的功能?我可以使用Underscore的_.filter
方法,但是我必须从顶部开始然后向下过滤.
I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore's _.filter
method, but I would have to start at the top and filter down.
推荐答案
递归是您的朋友.我更新了该函数以说明属性数组:
Recursion is your friend. I updated the function to account for property arrays:
function getObject(theObject) {
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = getObject(theObject[i]);
if (result) {
break;
}
}
}
else
{
for(var prop in theObject) {
console.log(prop + ': ' + theObject[prop]);
if(prop == 'id') {
if(theObject[prop] == 1) {
return theObject;
}
}
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
result = getObject(theObject[prop]);
if (result) {
break;
}
}
}
}
return result;
}
更新了jsFiddle: http://jsfiddle.net/FM3qu/7/
updated jsFiddle: http://jsfiddle.net/FM3qu/7/
这篇关于在嵌套数组深处按键查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文