AwesomeDevin / blog

Welcome to Devin's blog,I'm trying to be a fullstack developer and sticking with it !!!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

手写数组转树

AwesomeDevin opened this issue · comments

[{id:1, parentId: 0}, {id:2, parentId:1},{id:3, parentId:1}]
把这个数组从顶级分类递归查找子分类,最终构建一个树状数组。结果输出如下
[{id:1, parentId: 0,children:[{id:2, parentId:1},{id:3, parentId:1}]}]
parentId为0 的是根节点

支持新增、删除节点

const arr = [{id:1, parentId: 0}, {id:2, parentId:1},{id:3, parentId:1}]

function arr2tree(target, res = [], dep = 0){
   for(const item of target){
     if(item.parentId === dep){
       const node = { 
          ...item,
         children: []
       }
       res.push(node)
       arr2tree(target, node.children, dep+1)
     }
   }
  return res
}

console.log(arr2tree(arr))