手写代码之数组转tree

function listToTree(list, parentId = null) {
  const tree = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].parentId === parentId) {
      const node = {
        id: list[i].id,
        name: list[i].name,
        children: listToTree(list, list[i].id),
      };
      tree.push(node);
    }
  }
  return tree;
}

 

posted @ 2024-01-30 17:32  行走的蒲公英  阅读(5)  评论(0编辑  收藏  举报