js扁平数据转成树形数据

function treeDataTranslate(data, pid = '', list = []) {
  for (const item of data) {
    if (item.parent === pid) {
      const children = treeDataTranslate(data, item.id);
      const obj = { ...item };
      if (children.length) obj.children = children;
      list.push(obj);
    }
  }
  return list;
}
      const 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 treeDataTranslate(arr, pid = 0, list = []) {
        for (const item of arr) {
          if (item.pid === pid) {
            list.push(item);
          }
        }
        for (const sub of list) {
          sub.children = [];
          treeDataTranslate(arr, sub.id, sub.children);
        }
        return list;
      }
      console.log(treeDataTranslate(arr));

猜你喜欢

转载自blog.csdn.net/m0_56274171/article/details/123739687