递归转化树形结构

118 阅读1分钟

snipaste20230519_112155.jpg

1. 首先分析数据的关联关系

2. 封装递归函数根据关联关系转化层级结构

封装公共方法

 *
 * 功能:从list中找到pid为rootValue的元素,并以数组的格式返回
 * list: 是一个数组
 * rootValue: 是某个节点的id
*/

export function transListToTreeData(list, rootValue) {
  const arr = []
  list.forEach(item => {
    if (item.pid === rootValue) {
      // 找到了匹配的节点
      // 当前节点的id 和 当前节点的子节点的pid是相等的
      const children = transListToTreeData(list, item.id) 
      // 找到的节点的子节点
      item.children = children
      arr.push(item)
    }
  })
  return arr
}

获取完的组织数据使用转化方法转化成树形

  this.getDepartment() // 调用获取数据的接口
},
methods: {
  // 封装好方法
  async getDepartment() {
    const result = await getDepartment()
    this.depts = transListToTreeData(result, 0)
  }
}

总结:递归特点

  • 一般用来处理未知层级的数据
  • 递归要有跳出条件
  • 自身调用自身时参数不能重复