如何封装一个平铺数组转tree(树)的工具?

160 阅读1分钟
// 把平铺数组结构转为tree结构
export function tranListToTreeData(arr) {
  const newArr = []
  // 1. 构建一个字典,能根据id快速找到对象
  const map = {}
  // map 格式 {'01':{id:"02", pid:"01", "name":"小张" }}
  arr.forEach(item => {
    // 为了计算方便 同意添加children
    item.children = []
    const key = item.id
    map[key] = item
  })
  // 2.对于arr中的每一项 如果没有父元素则直接添加到新数组中 如果有父元素就把当前对象添加到父元素的children中
  arr.forEach(item => {
    const parent = map[item.pid]
    if (parent) {
      parent.children.push(item)
    } else {
      newArr.push(item)
    }
  })
  return newArr
}