SOURCE

// ⼊参格式参考:
const arr = [
  { id: 1, name: "i1" },
  { id: 2, name: "i2", parentId: 1 },
  { id: 4, name: "i4", parentId: 3 }, 
  { id: 6, name: "i6", parentId: 3 },
  { id: 3, name: "i3", parentId: 2 },
  { id: 8, name: "i8", parentId: 7 }
];
// { 1 - 2 - 3 - 4 }, { 8 }
// 出参格式可⾃⾏设计
// function buildTree(data) {
//   // a = [{ name: 'i1', id: 1, children: [ { name: 'i2', id: 2 }] }]
//   const arr = data.sort((a, b) => a.id - b.id);
//   const a = []
//   const id = new Set();
//   function has(b, c) {
//     if (b.id === c.parentId) return b;
//     if (b.children) {
//         for (let i = 0; i < b.children.length; i++) {
//             if (has(b.children[i], c)) return has(b.children[i], c);
//         }
//     }
//     return false;
//   }
//   arr.forEach((g) => {
//       id.add(g.id)
//   });
//   arr.forEach((g) => {
//       if (g.parentId && id.has(g.parentId)) {
//           return;
//       }
//       a.push(g);
//   });
//   arr.forEach((d) => {
//       a.forEach((e) => {
//           const f = has(e, d);
//           if (f) {
//               if (!f.children) {
//                   f.children = [];
//               }
//               f.children.push(d);
//           }
//       });
//   })
//   return a;
// }

// console.log(buildTree(arr));

function buildTree(data) {
  let i = 0;
  function has(parentId, c) {
    for (let i = 0; i < c.length; i++) {
      if (parentId === c[i].id) return c[i];
      if (c[i].children) {
        return has(parentId, c[i].children);
      }
    }
    return false;
  }
  while(i !== data.length - 1) {
    if (data[i].parentId) {
      const target = has(data[i].parentId, data);
      console.log(data[i]);
      console.log(target);
      if (target) {
        if (!target.children) target.children = [];
        target.children.push(data[i]);
        data.splice(i, 1);
      } else {
        i++
      }
    } else {
      i++
    }
  }

  return data;
};

console.log(buildTree(arr))
console 命令行工具 X clear

                    
>
console