当前位置:网站首页>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)
边栏推荐
猜你喜欢
5 个开源的 Rust Web 开发框架,你选择哪个?
Docker practical experience: Deploy mysql8 master-slave replication on Docker
分布式id解决方案
After class, watching the documentation and walking back to the lab, I picked up the forgotten SQL operators again
Initial JDBC programming
安装MYSQL遇到问题:write configuration file卡主
[Virtualization Ecological Platform] Platform Architecture Diagram & Ideas and Implementation Details
下课看着文档走回实验室,我重新拾起了遗忘的SQL运算符
Docker installs canal and mysql for simple testing and achieves cache consistency between redis and mysql
3.网页信息解析方法:Xpath与BeautifulSoup
随机推荐
AWS Amazon cloud account registration, free application for 12 months Amazon cloud server detailed tutorial
Initial JDBC programming
“带薪划水”偷刷阿里老哥的面经宝典,三次挑战字节,终成正果
deeplab implements its own remote sensing geological segmentation dataset
xmind使用指南(XMind具有下列哪些功能)
Use ODBC in Excel to read data from CDS view on SAP BTP platform
最全phpmyadmin漏洞汇总
keras自带数据集(横线生成器)
AWS亚马逊云账号注册,免费申请12个月亚马逊云服务器详细教程
Curl 命令使用
apisix-Getting Started
生命不息,刷题不止,简单题学习知识点
订song餐系统
Mysql环境变量的配置(详细图解)
502 bad gateway原因、解决方法
MySQL row-level locks (row locks, adjacent key locks, gap locks)
【虚拟化生态平台】树莓派安装虚拟化平台操作流程
Three-tier architecture service, dao, controller layer
一周精彩内容分享(第14期)
Read through the interface to call the artifact RestTemplate