当前位置:网站首页>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)
边栏推荐
- 【虚拟化生态平台】树莓派安装虚拟化平台操作流程
- The latest MySql installation teaching, very detailed
- St. Regis Takeaway Project: File Upload and Download
- Shengxin Weekly Issue 38
- IDEA configure method annotation automatic parameters
- 数据持久化技术——MP
- 生信周刊第38期
- Threading(in thread main)
- CWE4.8 -- 2022年危害最大的25种软件安全问题
- MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题)
猜你喜欢
「MySQL」- 基础增删改查
AWS亚马逊云账号注册,免费申请12个月亚马逊云服务器详细教程
[Virtualization Ecological Platform] Platform Architecture Diagram & Ideas and Implementation Details
学自动化测试哪个培训机构好 试听课程后就选了这个地方学习
JVS函数公式使用场景介绍
502 bad gateway原因、解决方法
分布式id解决方案
"JUC Concurrent Programming - Advanced" 06 - Immutability of Shared Models (Design of Immutable Classes | Use of Immutable Classes | Flyweight Pattern)
Distributed id solution
Experience innovation and iteration through the development of lucky draw mini-programs
随机推荐
Mysql环境变量的配置(详细图解)
[Virtualization ecological platform] Raspberry Pi installation virtualization platform operation process
Redis - Basics
JVS函数公式使用场景介绍
一文吃透接口调用神器RestTemplate
Threading(in thread main)
ApiPost 真香真强大,是时候丢掉 Postman、Swagger 了
便利贴--46{基于移动端长页中分页加载逻辑封装}
St. Regis Takeaway Project: File Upload and Download
多线程学习笔记-2.final关键字和不变性
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
The latest MySql installation teaching, very detailed
使用内存映射加快PyTorch数据集的读取
无法将“node.exe”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
deeplab implements its own remote sensing geological segmentation dataset
vb.net 画曲线
Docker build Mysql master-slave replication
【虚拟化生态平台】树莓派安装虚拟化平台操作流程
MySQL百万数据优化总结 一
DCM middleware family welcomes a new member