乐趣区

js树形结构根据关键字id查找节点路径

 const root = [{
        id: 1,
        child: [
            {
                id: 2,
                child: [
                    {
                        id: 4,
                        child: []},
                    {
                        id: 5,
                        child: []}
                ]
            },
            {
                id: 3,
                child: [
                    {
                        id: 6,
                        child: []},
                    {
                        id: 7,
                        child: []}
                ]
            }

        ]
    }]
function findPathbyId(tree,id,path){if(typeof path=='undefined'){path=[]
    }
    for(var i=0;i<tree.length;i++){var tempPath=[...path]
        tempPath.push(tree[i].id)
        if(tree[i].id==id){return tempPath}
        if(tree[i].child){let reuslt=findPathbyId(tree[i].child,id,tempPath)
            if(reuslt){return reuslt}
        }
    }
}
findPathbyId(root,6)
退出移动版