把平铺的数组结构转成树形结构的两种方式
1.普通方式转换
const arr = [
{id:"01", pid:"", "name":"老王" },
{id:"02", pid:"01", "name":"小张" }
]
//上面的结构说明: 老王是小张的上级
export function tranListToTreeData(list) {
// 1. 定义两个中间变量
const treeList = [] // 最终要产出的树状数组
let map = {} // 存储映射关系
// 2. 建立一个映射关系,遍历数组,并给每个元素补充children属性.
// 映射关系: 目的是让我们能通过id快速找到对应的元素
// 补充children:让后边的计算更方便
list.forEach(item => {
if (!item.children) {
item.children = []
}
map[item.id] = item
})
// 循环
list.forEach(item => {
// 对于每一个元素来说,先找它的上级
// 如果能找到,说明它有上级,则要把它添加到上级的children中去
// 如果找不到,说明它没有上级,直接添加到 treeList
const parent = map[item.pid]
// 如果存在上级则表示item不是最顶层的数据
if (parent) {
parent.children.push(item)
} else {
// 如果不存在上级 则是顶层数据,直接添加
treeList.push(item)
}
})
// 返回
return treeList
}
2.递归方式转换
<script> |
//把平铺的数组结构转成树形结构
const arr = [
{ '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研发部'},
{ 'id': 'd4', 'pid': 'd3', 'name': 'Java研发部-1组'}
]
// 在list找pid为第二次参数的元素,组成一个数组
function findChildren(list, pid) {
// 在list中根据pid来找元素
let treeList = []
treeList = list.filter(it => it.pid === pid)
/**
* [
* { 'id': '29', 'pid': '', 'name': '总裁办',children:[] },
* { 'id': '2c', 'pid': '', 'name': '财务部' },
* { 'id': 'd2', 'pid': '', 'name': '技术部'}
* ]
* */
treeList.forEach(item => {
item.children = findChildren(list, item.id)
})
return treeList
}
const treeList = findChildren(arr,'')
console.log('转换之后的树',treeList);
// console.log(arr)
// const arr1 = [
// { 'id': '29', 'pid': '', 'name': '总裁办',children: [] },
// { 'id': '2c', 'pid': '', 'name': '财务部', children:[
// { 'id': '2d', 'pid': '2c', 'name': '财务核算部',children: []},
// { 'id': '2f', 'pid': '2c', 'name': '薪资管理部',children: []},
// ] },
// { 'id': 'd2', 'pid': '', 'name': '技术部', children: [
// { 'id': 'd3', 'pid': 'd2', 'name': 'Java研发部',children: []}
// ]},
// ]
</script>