第一种:利用数组遍历方法
// list=[
// { 'id': '29', 'pid': '', 'name': '总裁办' },
// { 'id': '2c', 'pid': '', 'name': '财务部' },
// { 'id': '2d', 'pid': '2c', 'name': '财务核算部'},
// { 'id': '2f', 'pid': '2c', 'name': '薪资管理部'},
// { 'id': 'd2', 'pid': '', 'name': '技术部'},
// { 'id': 'd3', 'pid': 'd2', 'name': 'Java研发部'}
// ]
export function tranListToTreeData(list) {
const treeList = []; const map = {}
list.forEach(item => {
if (!item.children) {
item.children = []
}
// 建立映射关系,后面方便找到上级,并给每个元素补上children属性
map[item.id] = item
// map=== {
// 29: { 'id': '29', 'pid': '', 'name': '总裁办' },
// 2c: { 'id': '2c', 'pid': '', 'name': '财务部' },
// 2d: { 'id': '2d', 'pid': '2c', 'name': '财务核算部'},
// 2f: { 'id': '2f', 'pid': '2c', 'name': '薪资管理部'},
// d2: { 'id': 'd2', 'pid': '', 'name': '技术部'},
// d3: { 'id': 'd3', 'pid': 'd2', 'name': 'Java研发部'}
// }
})
list.forEach(item => {
const parent = map[item.pid]
if (parent) {
parent.children.push(item)
// 有上级,就添加到上级的children里
} else {
treeList.push(item)
// 没有上级,放到treeList中返回
}
})
return treeList
}
第二种:递归方法
export function findChildren(list, pid = '') {
// [
// { 'id': '29', 'pid': '', 'name': '总裁办' ,children=[]},
// { 'id': '2c', 'pid': '', 'name': '财务部', children=[......]},
// { 'id': 'd2', 'pid': '', 'name': '技术部' ,children=[...]}
// ]
const treeList = list.filter(item => item.pid === pid)
treeList.forEach(item => item.children = findChildren(list, item.id))
// 这递归调用了三层,可以一步一步去理解
return treeList
}