首页
关于
留言
壁纸
更多
直播
统计
友链
Search
1
好用的软件分享
401 阅读
2
最新Navicat 15 for MySQL破解+教程 正确破解步骤
271 阅读
3
面试常见问题100问
237 阅读
4
一个人要走的时候,千万别问原因
191 阅读
5
直击心灵的唯美句子
153 阅读
日常记录
后端
PHP
NodeJs
Python
Java
前端
JavaScript
数据库
MySQL
服务器
美文
微信开发
微信公众号
微信小程序
编程
登录
Search
标签搜索
mysql
python
django
express
面试
axios
thinkphp
PHP
励志
哲理
九九乘法表
node
cors
跨域
唯美句子
美文
文件上传
ajax
算法
jwt
公子初心
累计撰写
74
篇文章
累计收到
9
条评论
首页
栏目
日常记录
后端
PHP
NodeJs
Python
Java
前端
JavaScript
数据库
MySQL
服务器
美文
微信开发
微信公众号
微信小程序
编程
页面
关于
留言
壁纸
直播
统计
友链
搜索到
1
篇与
的结果
2024-05-14
JS实现无限级分类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> let arr = [ { id: 1, 'auth_name': '商品管理', pid: 0 }, { id: 2, 'auth_name': '商品添加', pid: 1 }, { id: 3, 'auth_name': '商品列表', pid: 1 }, { id: 4, 'auth_name': '用户管理', pid: 0 }, { id: 5, 'auth_name': '用户添加', pid: 4 }, { id: 6, 'auth_name': '商品添加1', pid: 2 }, ] function buildTree(items) { // 创建一个空的映射,用于存放每个id对应的节点 const map = new Map(); // 遍历数组,建立id到节点的映射,并为每个节点初始化children数组 items.forEach(item => { map.set(item.id, { ...item, children: [] }); }); // 遍历数组,将每个节点添加到其父节点的children数组中 items.forEach(item => { // 如果当前节点不是根节点(pid不为0) if (item.pid !== 0) { // 从映射中获取父节点 const parent = map.get(item.pid); // 如果父节点存在,将当前节点添加到父节点的children数组中 if (parent) { parent.children.push(map.get(item.id)); } } }); // 过滤出根节点(pid为0)并返回 return Array.from(map.values()).filter(node => node.pid === 0); } const tree = buildTree(arr); console.log(tree); console.log(JSON.stringify(tree, null, 2)) </script> </body> </html>
2024年05月14日
30 阅读
0 评论
0 点赞