問題描述
將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);
}
}
}
運行結果: