js 扁平数据结构转Tree

123 阅读1分钟
const testArr = [
  { 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 },
]

const getMap = (arr) => {
  const result = {}
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index]
    const pid = element.pid
    if (!result[pid]) {
      result[pid] = []
    }
    const pidArr = result[pid]
    pidArr.push(element)
  }
  return result
}

const map = getMap(testArr)

const arrToTree = (arr) => {
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index]
    const id = element.id
    const childrenArr = map[id]
    if (childrenArr) {
      element.children = childrenArr
      arrToTree(childrenArr)
    }
  }
  return arr
}

const tree = arrToTree(map[0])

console.log('tree', tree)