Back end returns data:

let list = [
        {
          id: "604e21feb205b95968e13129".pid: "".name: "President's office"
        },
        {
          id: "604e222bb205b95968e1312a".pid: "".name: "Administration Department"
        },
        {
          id: "604e223fb205b95968e1312b".pid: "".name: "Personnel department"
        },
        {
          id: "604e2251b205b95968e1312c".pid: "".name: "Finance Department"
        },
        {
          id: "604e2262b205b95968e1312d".pid: "604e2251b205b95968e1312c".name: "Financial Accounting Department"
        },
        {
          id: "604e227db205b95968e1312e".pid: "604e2251b205b95968e1312c".name: "Department of Tax Administration"
        },
        {
          id: "604e2297b205b95968e1312f".pid: "604e2251b205b95968e1312c".name: "Payroll Management department"
        },
        {
          id: "6051ad90e93db6522c1d00d2".pid: "".name: "Technical Department"
        },
        {
          id: "6051adb6e93db6522c1d00d3".pid: "6051ad90e93db6522c1d00d2".name: "Java R&d Department"
        },
        {
          id: "6051add6e93db6522c1d00d4".pid: "6051ad90e93db6522c1d00d2".name: "Python Development Department"
        },
        {
          id: "6051adefe93db6522c1d00d5".pid: "6051ad90e93db6522c1d00d2".name: "Php Development Department"
        },
        {
          id: "6051ae03e93db6522c1d00d6".pid: "".name: "Operations department"
        },
        {
          id: "6051ae15e93db6522c1d00d7".pid: "".name: "Marketing Department"
        },
        {
          id: "6051ae28e93db6522c1d00d8".pid: "6051ae15e93db6522c1d00d7".name: Beijing Business Division
        },
        {
          id: "6051ae3de93db6522c1d00d9".pid: "6051ae15e93db6522c1d00d7".name: Shanghai Business Division}];Copy the code

Recursive:

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);
      returnacc; }}, {});return arr;
}
root(list, "");
Copy the code

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, "");
Copy the code