I have this data
const data = [
{
name: "Car",
id: "19",
count: "20",
depth: "1",
children: [
{
name: "Wheel",
id: "22",
count: "3",
depth: "2",
children: [
{
name: "Engine",
id: "101",
count: "1",
depth: "3",
children: [
{
name: "Engine and Brakes",
id: "344",
count: "1",
depth: "4",
children: []
}
]
}
]
}
]
},
{
name: "Bike",
id: "3",
count: "12",
depth: "1",
children: [
{
name: "SpeedBike",
id: "4",
count: "12",
depth: "2",
children: []
}
]
}
];
I want to pass in multiple category ids as follows [’22’, ‘3’] and be able to get all the children of the passed category ids which should look like this:
[
{
name: "Engine",
id: "101",
count: "1",
},
{
name: "Engine and Brakes",
id: "344",
count: "1",
},
{
name: "SpeedBike",
id: "4",
count: "12",
}
]
If no category id is passed I want to be able to see the parent and the direct children as default. like below:
[
{
name: "Car",
id: "19",
count: "20"
},
{
name: "Wheel",
id: "22",
count: "3"
},
{
name: "Bike",
id: "3",
count: "12",
},
{
name: "SpeedBike",
id: "4",
count: "12"
}
]
If the category id passed does not have children I want to return an empty array.:
[]
I want to avoid using for
foreach
and while
. How can I achieve this? I have tried using map
and filter
but no luck. Can someone please help? What is the best approach to this?
I am using js and ts.
The nested array can be deep with multiple deep levels.
3
Answers
Below is a simple reference for you to using Recursive_function to do it
We are still going to use the approach described in your previous related question. However, we are going to update the algorithm slightly.
Now stack will store categories with additional
isDesired?: boolean
prop, which indicates that this category is the descendant of the category with the id that we are looking for.If the category’s id is in
categoryIds
then we push its children in the stack with theisDesired: true
.We decide to put children of category into
foundChildren
under the condition: if the category id is incategoryIds
orcategory.isDesired
istrue
Playground with comments
Call this function –
Include this function in the file –
Example –