编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
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 },
]

function getListChildren(arr, total) {
    const list = []

    arr.forEach(item => {
        if (item.pid === 0) {
            const newItem = {item, ...list = total.filter(({ pid }) => pid === item.id)}
            getListChildren(item.list, arr)
            list.push(item)

        }
    })


    return list
}

//console.log(getListChildren(arr, arr))

/**
 * 递归查找,获取children
 */
const getChildren = (data, result, pid) => {
    for (const item of data) {
        if (item.pid === pid) {
            const newItem = { ...item, children: [] };
            result.push(newItem);
            getChildren(data, newItem.children, item.id);
        }
    }
}

/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
    const result = [];
    getChildren(data, result, pid)
    return result;
}

console.log(arrayToTree(arr, 0))

// 一群孩子知道自己是谁,知道他爸爸是谁
// 所有人都知道老祖宗的名字
let arr = [
 
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
  { id: 1, name: '部门1', pid: 0 },
]

// 目的揪出他们家老祖宗
function arrayToTree2(items) {
  const result = [];   //  老祖宗的轿子
  const itemMap = {};  // 建一个仓库
    
  // 先转成map存储
  for (const item of items) { // 给每个人建个仓库,再预留儿子的位置
    itemMap[item.id] = {...item, children: []}
  }
  
  for (const item of items) { // 问问每一个孩子的情况
    const id = item.id;  //孩子叫啥
    const pid = item.pid;  // 孩子他爸叫啥
    const treeItem =  itemMap[id]; // 孩子的仓库
    if (pid === 0) { // 找到了老祖宗直接拉轿子里带走
      result.push(treeItem);
    } else { // 这个孩子不是老祖宗
      if (!itemMap[pid]) {  // 问问这有没有他爸的仓库,没有就用他爸的名字建个新的,记得留好自己的位置
        itemMap[pid] = {
          children: [],
        }
      }
      // 现在孩子他爸的仓库都有了
      itemMap[pid].children.push(treeItem) // 把孩子放在他爸仓库预留的位置上
    }
  }
  // 每个孩子都找到了自己的爸爸,老祖宗也找到了,抬轿拉走
  return result;
}

console.log(arrayToTree2(arr))