当前位置:网站首页>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)
边栏推荐
- Summary of several defragmentation schemes for MySQL (to solve the problem of not releasing space after deleting a large amount of data)
- [Go Affair] See through Go's collections and slices at a glance
- 5 个开源的 Rust Web 开发框架,你选择哪个?
- 数据持久化技术——MP
- 关于IDEA开发工具的介绍
- R语言做面板panelvar例子
- Experience innovation and iteration through the development of lucky draw mini-programs
- JVS应用中心
- LeetCode 1161.最大层内元素和:层序遍历
- xmind使用指南(XMind具有下列哪些功能)
猜你喜欢

ESP8266-Arduino编程实例-HDC1008温度湿度传感器驱动

ESP8266-Arduino编程实例-MCP9808数字温度传感器驱动

生信周刊第38期

才22岁!这位'00后'博士拟任职985高校!

3D激光SLAM:LeGO-LOAM论文解读---完整篇

In PLC communication error or timeout or download the prompt solution of the model

file contains vulnerabilities

apisix-Getting Started

Cloudera Manager —— 端到端的企业数据中心管理工具

JVS应用中心
随机推荐
AWS亚马逊云账号注册,免费申请12个月亚马逊云服务器详细教程
Addition logic for SAP Commerce Cloud Product Review
[ 图 论 ]二分图判定及其匹配(基础+提高)
Distributed Transactions - Introduction to Distributed Transactions, Distributed Transaction Framework Seata (AT Mode, Tcc Mode, Tcc Vs AT), Distributed Transactions - MQ
瑞吉外卖项目:新增菜品与菜品分页查询
After Effects 教程,如何在 After Effects 中修复曝光不足的镜头?
无法将“node.exe”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
MySQL 行级锁(行锁、临键锁、间隙锁)
Yarn安装配置(vsftpd安装配置)
MySQL 的 limit 分页查询及性能问题
准确率(Accuracy)、精度(Precision)、召回率(Recall)和 mAP 的图解
AWS Amazon cloud account registration, free application for 12 months Amazon cloud server detailed tutorial
Mysql环境变量的配置(详细图解)
三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键
3D激光SLAM:LeGO-LOAM论文解读---点云分割部分
才22岁!这位'00后'博士拟任职985高校!
生信周刊第38期
Data Lake (19): SQL API reads Kafka data and writes it to Iceberg table in real time
基于Multisim的函数信号发生器–方波、三角波、正弦波[通俗易懂]
Data Persistence Technology - MP