Let’s say I have an object:
JavaScript
x
20
20
1
[
2
{
3
'title': "some title"
4
'channel_id':'123we'
5
'options': [
6
{
7
'channel_id':'abc'
8
'image':'http://asdasd.com/all-inclusive-block-img.jpg'
9
'title':'All-Inclusive'
10
'options':[
11
{
12
'channel_id':'dsa2'
13
'title':'Some Recommends'
14
'options':[
15
{
16
'image':'http://www.asdasd.com' 'title':'Sandals'
17
'id':'1'
18
'content':{
19
20
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.
Advertisement
Answer
Recursion is your friend. I updated the function to account for property arrays:
JavaScript
1
30
30
1
function getObject(theObject) {
2
var result = null;
3
if(theObject instanceof Array) {
4
for(var i = 0; i < theObject.length; i++) {
5
result = getObject(theObject[i]);
6
if (result) {
7
break;
8
}
9
}
10
}
11
else
12
{
13
for(var prop in theObject) {
14
console.log(prop + ': ' + theObject[prop]);
15
if(prop == 'id') {
16
if(theObject[prop] == 1) {
17
return theObject;
18
}
19
}
20
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
21
result = getObject(theObject[prop]);
22
if (result) {
23
break;
24
}
25
}
26
}
27
}
28
return result;
29
}
30
updated jsFiddle: http://jsfiddle.net/FM3qu/7/