const data= [
{
"category": "cat1",
"items": ["item5","item6"],
"subcategories": [
{
"category": "cat11",
"items": ["item1","item2","item3","item4"],
"subcategories" [
{
"category": "cat111",
"items": ["item7","item8","item9","item0"],
"subcategories" []
},
{
"category": "cat112",
"items": ["item7","item8","item9","item0"],
"subcategories" []
}
]
},
{
"category": "cat12",
"items": ["item1","item2","item3","item4"],
"subcategories" [
{
"category": "cat121",
"items": ["item7","item8","item9","item0"],
"subcategories" []
}
]
}
]
}
]
This is a data structure with nested subcategories and items. The goal of the recursive function in TypeScript is to determine the total count of items under each category.
For instance:
cat1 : 22
cat11 : 12
cat11 : 8
cat121 : 4
An implementation has been attempted but it does not provide the desired results.
this.getItemCount(this.data, 0);
/**
* Recursive method to calculate the number of items in a category
*/
getItemCount(data: any[], itemCount: number) {
data.forEach((category) => {
itemCount = itemCount + category.items.length;
if(category.subcategories.length) {
this.getItemCount(category.subcategories, itemCount);
}
category.count = itemCount;
itemCount = 0;
});
}