I am currently trying to access an object and its properties but I can't seem to find a way to get objects that are not the first items in their respective children array. It can find numbers only if they're first in the array, but I think that I did the wrong thing in my function, and I am not quite sure how to fix it. What could be my mistakes and how do I fix this?
Here is the tree:
{
name: "One",
ids: {
id: 1,
level: 0
},
children: [
{
name: "Two",
ids: {
id: 2,
level: 1
},
children: [
{
name: "Three",
ids: {
id: 3,
level: 2
},
children: [
{
name: "Five",
ids: {
id: 5,
level: 3
},
children: [
{
name: "Eight",
ids: {
id: 8,
level: 4
},
children: []
},
{
name: "Nine",
ids: {
id: 9,
level: 4
},
children: []
},
{
name: "Ten",
ids: {
id: 10,
level: 4
},
children: []
}
]
}
]
},
{
name: "Four",
ids: {
id: 4,
level: 2
},
children: [
{
name: "Six",
ids: {
id: 6,
level: 3
},
children: []
},
{
name: "Seven",
ids: {
id: 7,
level: 3
},
children: []
}
]
}
]
}
]
}
And here is my function:
findObj(obj, id) {
if(obj.ids.id == id) {
return obj;
}
else if(obj.children.length != 0) {
for(var i in obj.children) {
var temp = findObj(obj.children[i], id);
if(temp != undefined) {
return temp;
}
}
}
}