Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写数组转树 #104

Open
AwesomeDevin opened this issue Sep 20, 2023 · 0 comments
Open

手写数组转树 #104

AwesomeDevin opened this issue Sep 20, 2023 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

AwesomeDevin commented Sep 20, 2023

[{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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant