1.包array-to-tree
import arrayToTree from 'array-to-tree'
export function transArray(arr){
return arrayToTree(arr,{
parentProperty: 'parentId', //指向父節(jié)點(diǎn)的屬性名稱,默認(rèn)"parend_id"
childrenProperty:'arrs' //存儲(chǔ)子節(jié)點(diǎn)的屬性名稱,默認(rèn)"children"
customID: 'Id' //唯一節(jié)點(diǎn)標(biāo)識(shí)符,默認(rèn)"id"
})
}
2.字典映射
let arr = [
{ Id: 1, name: '數(shù)據(jù)1', parentId: null },
{ Id: 2, name: '數(shù)據(jù)1-1', parentId: 1 },
{ Id: 3, name: '數(shù)據(jù)1-1-1', parentId: 2 },
{ Id: 4, name: '數(shù)據(jù)1-2', parentId: 1 },
{ Id: 5, name: '數(shù)據(jù)2', parentId: null },
{ Id: 6, name: '數(shù)據(jù)2-1', parentId: 5 }
]
function toTree(arg){
const newArr = [];
const map = {} //存儲(chǔ)映射關(guān)系
arg.forEach(item=>{
if(!item.children){
item.children = []
}
map[item.Id] = item
})
arg.forEach(item=>{
if(item.parentId){
map[item.parentId].children.push(item)
}else{
newArr.push(item)
}
})
return newArr
}
toTree(arr)