I have a simple function looks at an object in an array. If it doesn't find a match based on a property it checks if it has children and then checks each of those for a property value.
It seems to work as expected through the first object with children, however it is not hitting that third layer.
The object is something like this:
data = [{
title: 'Home',
route: '/reports/home',
},
{
title: 'Layer 2',
children: [
{ title: 'Title 1', route: '/reports/title1' },
{ title: 'Title 2', route: '/reports/title2' },
],
},
{
title: 'Layer 3',
children: [
{ title: 'Title 3', route: '/reports/title3' },
{ title: 'Title 4', route: '/reports/title4' },
],
}];
lookUpTitle = navGroup => {
for (let item of navGroup) {
if (item.route && item.route.toLowerCase() === '/reports/title3') {
console.log(item.title)
return item.title;
} else {
if (item.children) {
return this.lookUpTitle(item.children);
}
}
}
};
lookUpTitle(data)
I'm simply calling the function and passing in the array as above.
I can find Title 2 just fine, but the function will not iterate through to the third object in the array if I'm looking for Title 3 or 4. What am I missing?
What is happening
To understand why the loop stops, let's write what is happening step by step:
item
takes the value of the first object. (Title = Home).if
condition is not met and item
doesn't contain children
item
takes the value of the second object.if
condition is not met but item
contains children
lookUpTitle()
thus the loop stops.So the loop will always stop if an object doesn't meet the if
condition and contains children
.
How to fix it
In order to fix it, we have to track the recursive results. Check if a result is found through the recursive call of lookUpTitle()
. If not, continue to loop, if found, you can return it. This method assumes you only want the first result found and not all existing results.
lookUpTitle = navGroup => {
for (let item of navGroup) {
if (item.route && item.route.toLowerCase() === '/reports/title3') {
return item.title;
} else {
if (item.children) {
var res = this.lookUpTitle(item.children);
if(res != undefined)
return res;
}
}
}
};