Ask the question of js, how to deal with this kind of recursion?

problem description

want to implement a recursion, but the foundation of js is poor, so I don"t know how to implement it.

related codes

/ / Please paste the code text below (do not replace the code with pictures)

var array = [
        {
            name: "",
            component: () => import("@/views/setting/ManageList"),
            meta: {
                title: "0",
                roles: [0, 1, 2, 3, 4]
            },
            children: [
                {
                    component: () => import("@/views/setting/ManageList"),
                    meta: {
                        title: "1",
                        roles: [0, 1]
                    }
                }, {
                    component: () => import("@/views/setting/ManageList"),
                    meta: {
                        title: "2",
                        roles: [0]
                    }
                }
            ]
        }
    ]

what result do you expect?

topic description

the data you hope to get in the end is as follows:

var array = [
        {
            name: "",
            component: () => import("@/views/setting/ManageList"),
            meta: {
                title: "0",
                roles: [0, 1, 2, 3, 4]
            },
            children: [
                {
                    component: () => import("@/views/setting/ManageList"),
                    meta: {
                        title: "1",
                        roles: [0, 1]
                    }
                }
            ]
        }
    ]
function filterAsyncRouter (array, id) {
        let res = []
        array.filter(item => {
            if (item.meta.roles.includes(id)){
                if (item.children){
                    item.children = filterAsyncRouter(item.children, id)
                }
                res.push(item)
            }
        })
        console.log("res", res)
    }
    filterAsyncRouter(array, 1);

I still don"t think it"s right when I try to write it. No, no, no.
may not be expressed clearly. If the parent node has 1, return the parent node. If both the parent node and child node have 1, only the child node with 1 needs to be returned. Child nodes without 1 do not need to return ~

Mar.28,2022

well, as I understand it, you should want Filter to drop the roles that does not contain 1 in the child node.
you try the following

function loop(arr,idx){
  for(var i=0,newArr=[];i<arr.length;iPP){
    if(arr[i].meta.roles.indexOf(idx)!=-1)
      newArr.push(arr[i]);
    if(arr[i].children)
      newArr[i].children = loop(arr[i].children,idx);
  }
  return newArr;
}

loop(arr,1);
Menu