What I missed, when dealing with recursion?

there is such an array
const dataArr = [
{
 "id": 28,
 "title": "Free content",
 "children": [
{
 "id": 29,
 "title": "Lorem", 
 "children": [
{
 "id": 32,
 "title": "Lorem", 
 "children": []
},
{
 "id": 30,
 "title": "Lorem", 
 "children": []
}
],
 }, 
{
 "id": 33,
 "title": "Lorem", 
 "children": [
{
 "id": 35,
 "title": "Lorem", 
 "children": []
 }, 
{
 "id": 34,
 "title": "Lorem", 
 "children": []
}
],
}
],
}
]

and then there are some variable that overwrites the id of any object
let objID = 29
is the function(recursion) which processes this array
function test1(arr) {
 let res = [];
 arr.forEach(item => {
 if (item.id === objID) {
Res. push(item)
 } else {
test1(item.children)
}
});
 console.log('funtion test1', res)
 return res
}
console.log('result', test1(dataArr))

expected result
result {
 "id": 29,
 "title": "Lorem", 
 "children": [
{
 "id": 32,
 "title": "Lorem", 
 "children": []
},
{
 "id": 30,
 "title": "Lorem", 
 "children": []
}
],
 },

but the result's the same and it is not clear why
5e999ec2c2c13812670391.jpeg
how to make him empty answers were not given? what am I doing wrong?
April 19th 20 at 12:32
1 answer
April 19th 20 at 12:34
Solution
Replace
function test1(arr)
on
function test1(arr) {
 return arr.reduce((res, item) => {
 if (item.id === objID) {
Res. push(item);
 } else {
Res. push(...test1(item.children));
}
 return res;
 }, []); 
}
thank you)) I'm going to read a documentary about reduce )) - alfreda_Dibbert commented on April 19th 20 at 12:37

Find more questions by tags RecursionJavaScript