I am facing a data challenge with the following structure:
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: []
}
]
}
];
My goal is to filter out specific categories based on their IDs, as shown below:
[
{
name: "Engine and Brakes",
id: "344",
count: "1",
},
{
name: "SpeedBike",
id: "4",
count: "12",
}
]
If no category ID is provided, I need to display both the parent and its direct children by default:
[
{
name: "Car",
id: "19",
count: "20"
},
{
name: "Wheel",
id: "22",
count: "3"
},
{
name: "Bike",
id: "3",
count: "12",
},
{
name: "SpeedBike",
id: "4",
count: "12"
}
]
In cases where the passed category ID has no children, an empty array should be returned:
[]
I aim to solve this without utilizing for
, foreach
, or while
loops. I have attempted using map
and filter
methods without success. Seeking advice on the best approach for this scenario. Thank you!
Note: I am working with JavaScript (js) and TypeScript (ts).
The nested array can have multiple deep levels.