一維權限數組生成樹結構權限

問題描述

將let authList = [
    {
        id:"1",
        parentId:"0"
    },{
        id:"2",
        parentId:"0"
    },{
        id:"21",
        parentId:"2"
    },{
        id:"211",
        parentId:"21"
    }
]
轉成
let authTree = {  
        id:"0", 
        children:[  
            {  
                id:"1",  
                parentId:"0", 
                treeId:"0-1" 
                children:[]  
            },{  
                id:"2",  
                parentId:"0",  
                treeId:"0-2"
                children:[  
                    {  
                        id:"21",  
                        parentId:"2",  
                        treeId:"0-2-21"
                        children:[  
                            {  
                                id:"211",  
                                parentId:"21",
                                treeId:"0-2-21-211" 
                            }  
                        ]  
                    }  
                ]  
            }  
        ]  
    }  

代碼如下:

    /*
    * authList:需要被轉換的一維數組
    * authTreeRootNode:權限樹根節點
    * idMap:記錄樹結構的id路徑
    */
    function convertToTree(authList,authTreeRootNode,idMap){
        authTreeRootNode.children = [];
        let parntId = authTreeRootNode.id
        for(let i = authList.length-1;i>=0;i--){
            if(authList[i].parentId == parntId){
                idMap[authList[i].id] = idMap[authList[i].parentId]?`${idMap[authList[i].parentId]}-${authList[i].id}` : authList[i].id;
                authList[i].treeId = idMap[authList[i].id];
                authTreeRootNode.children.push(authList[i]);
                convertToTree(authList,authTreeRootNode[authTreeRootNode.children.length-1],idMap);
            }
        }
    }

運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章