It seems to me that the code for the 2nd item in items is never reached in the for loop.
How to fix this method?
class Item {
items: Item[] = [];
constructor(public id: string){}
}
function getItembyIdRecursively(id: string, items: Item[]) : Item |undefined{
for(const item of items)
{
if(item.id === id)
{
return item;
}
else
{
return getItembyIdRecursively(id,item.items);
}
}
return undefined;
}
const item1 = new Item("1");
const item2 = new Item("2");
item1.items.push(new Item("1.2"));
const items = [item1, item2];
const foundItem = getItembyIdRecursively("2", items);
console.log(foundItem.id);
You can find a repro sample here:
>Solution :
The problem is your else statement, you are returning the result in all cases, even if it is undefined. Basically since the first Item has children, you return the result of search in its children, and since the id is not matched, you get undefined.
for(const item of items)
if(item.id === id)
{
return item;
}
else
{
const elem = getItembyIdRecursively(id,item.items);
if (elem) {
return elem;
}
}
return undefined;
}