js方法 : 使用递归将数组转为树形结构

304 阅读2分钟

后端返回数据:

let list = [
        {
          id: "604e21feb205b95968e13129",
          pid: "",
          name: "总裁办"
        },
        {
          id: "604e222bb205b95968e1312a",
          pid: "",
          name: "行政部"
        },
        {
          id: "604e223fb205b95968e1312b",
          pid: "",
          name: "人事部"
        },
        {
          id: "604e2251b205b95968e1312c",
          pid: "",
          name: "财务部"
        },
        {
          id: "604e2262b205b95968e1312d",
          pid: "604e2251b205b95968e1312c",
          name: "财务核算部"
        },
        {
          id: "604e227db205b95968e1312e",
          pid: "604e2251b205b95968e1312c",
          name: "税务管理部"
        },
        {
          id: "604e2297b205b95968e1312f",
          pid: "604e2251b205b95968e1312c",
          name: "薪资管理部"
        },
        {
          id: "6051ad90e93db6522c1d00d2",
          pid: "",
          name: "技术部"
        },
        {
          id: "6051adb6e93db6522c1d00d3",
          pid: "6051ad90e93db6522c1d00d2",
          name: "Java研发部"
        },
        {
          id: "6051add6e93db6522c1d00d4",
          pid: "6051ad90e93db6522c1d00d2",
          name: "Python研发部"
        },
        {
          id: "6051adefe93db6522c1d00d5",
          pid: "6051ad90e93db6522c1d00d2",
          name: "Php研发部"
        },
        {
          id: "6051ae03e93db6522c1d00d6",
          pid: "",
          name: "运营部"
        },
        {
          id: "6051ae15e93db6522c1d00d7",
          pid: "",
          name: "市场部"
        },
        {
          id: "6051ae28e93db6522c1d00d8",
          pid: "6051ae15e93db6522c1d00d7",
          name: "北京事业部"
        },
        {
          id: "6051ae3de93db6522c1d00d9",
          pid: "6051ae15e93db6522c1d00d7",
          name: "上海事业部"
        }
     ];

递归:

reduce:

function root(list, pid) {
  let arr = [];
  
  list.reduce((acc, cur) => {
    if (cur.pid === pid) {
      acc = root(list, cur.id);
      if (acc.length > 0) {
        cur.children = acc;
      }
      arr.push(cur);
      return acc;
    }
  }, {});
  return arr;
}
root(list, "");

forEach:

function root(list, pid) {
  let arr = [];
  let temp;
  
  list.forEach(item => {
    if (item.pid === pid) {
      let obj = item;
      temp = root(list, item.id);
      if (temp.length > 0) {
        obj.children = temp;
      }
      arr.push(obj);
    }
  })
 return arr;
}
root(list, "");