B
B
BKaiyrbekov2020-04-17 15:19:28
JavaScript
BKaiyrbekov, 2020-04-17 15:19:28

What did I miss when working with recursion?

there is such an array

const dataArr = [
    {
          "id": 28,
          "title": "Бесплатные материалы",
          "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 there is also some kind of variable that overwrites the id of any object and there is a function (recursion) that processes this array
let objID = 29
funtion 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 is this, and it is not clear why,
5e999ec2c2c13812670391.jpeg
but how to make it so that it does not give empty answers? what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SimBioT19, 2020-04-17
@BKaiyrbekov

Replace
funtion test1(arr)
with

funtion test1(arr) {
       return arr.reduce((res, item) => {
          if (item.id === objID) {
            res.push(item);
          } else {
          res.push(...test1(item.children));
          }
           return res;
        }, []);       
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question