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; } } } }
Answer
You can do this using recursive approach with a single forEach
loop.
const data = {"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":[]}]}]}]} function findObj(obj, id) { let result = null; if (obj.ids.id === id) result = obj; if (obj.children) { obj.children.forEach(c => { if (!result) result = findObj(c, id) }) } return result; } console.log(findObj(data, 6)) console.log(findObj(data, 5)) console.log(findObj(data, 1))