1.包array-to-tree
import arrayToTree from 'array-to-tree'
export function transArray(arr){
return arrayToTree(arr,{
parentProperty: 'parentId', //指向父节点的属性名称,默认"parend_id"
childrenProperty:'arrs' //存储子节点的属性名称,默认"children"
customID: 'Id' //唯一节点标识符,默认"id"
})
}
2.字典映射
let arr = [
{ Id: 1, name: '数据1', parentId: null },
{ Id: 2, name: '数据1-1', parentId: 1 },
{ Id: 3, name: '数据1-1-1', parentId: 2 },
{ Id: 4, name: '数据1-2', parentId: 1 },
{ Id: 5, name: '数据2', parentId: null },
{ Id: 6, name: '数据2-1', parentId: 5 }
]
function toTree(arg){
const newArr = [];
const map = {} //存储映射关系
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)