SOURCE

/**
 * tree
 */

let arr = [
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 }
]

/**
 * 转换成tree结构
 */
function switchToTree(arr) {
  let tree = []
  let idObj = {}
  arr.forEach((item) => {
    idObj[item.id] = { ...item, children: [] }
  })

  // console.log(idObj)

  arr.forEach((item) => {
    if (item.pid == 0) {
      tree.push(idObj[item.id])
    } else {
      let parent = idObj[item.pid]
      if (!idObj[item.pid]) {
        idObj[item.pid] = { children: [] }
      }

      idObj[item.pid].children.push(idObj[item.id])
    }
  })

  console.log(tree)
}

switchToTree(arr)

function toTree(data) {
  let res = []
  let map = {}

  data.forEach((item) => {
    map[item.id] = item
  })

  data.forEach((item) => {
    let parent = map[item.pid]

    if (parent) {
      parent.children || (parent.children = []).push(item)
    } else {
      res.push(item)
    }
  })

  return res
}

console.log(toTree(arr))
console 命令行工具 X clear

                    
>
console