I am dealing with a recursive list of items
in Angular/TypeScript. My goal is to only show items
when they are either active=true;
themselves or if any of their children or grandchildren are also active=true
.
data.json
[
{
"active": true,
"items": [
{
"active": false,
"items": [
{
"active": false,
"items": []
},
{
"active": false,
"items": []
}
]
},
{
"active": false,
"items": [
{
"active": true,
"items": []
}
]
},
{
"active": true,
"items": [
{
"active": true,
"items": []
}
]
}
]
}
]
Despite my current recursive method, it still does not handle nested items and incorrectly returns false
for all parents when I set the deepest item as active=false;
The issue arises from the fact that when an item
had children, the recursion would simply continue (
return this.hasActiveChildren(i);
) without considering the current item.active
status.
method.ts
public hasActiveChildren(item: Item): boolean {
if (item.items === null || item.items.length <= 0) {
return false;
}
return item.items.some(i => {
if (i.items === null || i.items.length <= 0) {
return i.active;
} else {
return this.hasActiveChildren(i);
}
});
}
A second method performs better by returning false
for a parent if all immediate children are active=false;
. Nonetheless, it still overlooks the children´s children.
updatedMethod.ts
public hasActiveChildren(item: Item): boolean {
for (const i of item.items) {
if (i.active === true) {
return true;
} else if(i.items=== null || i.items.length <= 0) {
return this.hasActiveChildren(i);
}
}
return false;
}
I might need to specify:
- I have a recursive list of
items
with an unknown depth - Each
item
possesses anactive
property - I aim to develop a method that yields
true
when any children or children´s children'sactive
property is set totrue
- Two methods have been created to address this issue, but neither fully solves it