当前位置:网站首页>JS列表数据通过递归实现树形结构
JS列表数据通过递归实现树形结构
2022-07-31 11:49:00 【cs1330】
const list = [
{ pid: null, id: 1, data: "1" },
{ pid: 1, id: 2, data: "2-1" },
{ pid: 1, id: 3, data: "2-2" },
{ pid: 2, id: 4, data: "3-1" },
{ pid: 3, id: 5, data: "3-2" },
{ pid: 4, id: 6, data: "4-1" },
];
function List(list, root) {
const arr = []
// 先找到父节点
list.forEach(item => {
if (item.pid === root) {
// 将父节点添加到数组里
arr.push(item)
// 再次递归调用函数,传入数组跟当前每一项的id跟 pid 去寻找,找到相同的则就是子级
const children = List(list, item.id)
// console.log(children)
// 再次判断有没有存在没有子级情况,返回的是一个空数组
if (children.length > 0) {
// 有子级就给每一项的item添加个children属性
item.children = children
}
}
})
return arr
}
const arr = List(list, null)
console.log(arr)
边栏推荐
猜你喜欢
随机推荐
Curl 命令使用
Docker安装canal、mysql进行简单测试与实现redis和mysql缓存一致性
Docker实践经验:Docker 上部署 mysql8 主从复制
IDEA 配置方法注释自动参数
Docker搭建Mysql主从复制
apisix-Getting Started
Is the working process of the belt you know the story - actionreducerstore
MySQL limit paging query and performance issues
【软件工程之美 - 专栏笔记】33 | 测试工具:为什么不应该通过QQ/微信/邮件报Bug?
一、excel转pdf格式jacob.jar
Unix知识:shell详细解读
pycharm汉化教程(碧蓝幻想汉化插件安装)
初始JDBC 编程
在 Excel 内使用 ODBC 消费 SAP ABAP CDS view
ApiPost 真香真强大,是时候丢掉 Postman、Swagger 了
The most complete phpmyadmin vulnerability summary
In PLC communication error or timeout or download the prompt solution of the model
Cloudera Manager —— 端到端的企业数据中心管理工具
Distributed id solution
"JUC Concurrent Programming - Advanced" 06 - Immutability of Shared Models (Design of Immutable Classes | Use of Immutable Classes | Flyweight Pattern)