JavaScript将一个包含父子关系的扁平化数组转换成树形菜单
发表于:2023-05-18 09:29:30浏览:2724次
以下是将一个包含父子关系的扁平化数组转换成树形菜单的JavaScript递归函数的示例:
function generateTree(arr, parentId = null) {
const tree = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].parent_id === parentId) {
const node = {
id: arr[i].id,
name: arr[i].name,
children: generateTree(arr, arr[i].id)
};
tree.push(node);
}
}
return tree;
}
该函数接受一个包含父子关系的扁平化数组和可选的parentId参数作为输入。它会遍历数组并找到所有具有指定父ID的节点,将它们转换为对象,并在children属性中递归调用它自己以获取每个节点的子节点。最终,它将返回一个树形菜单对象数组。
例如,假设我们有以下扁平化数组:
const flatArray = [
{ id: 1, parent_id: null, name: 'Home' },
{ id: 2, parent_id: 1, name: 'About' },
{ id: 3, parent_id: 1, name: 'Contact' },
{ id: 4, parent_id: 2, name: 'History' },
{ id: 5, parent_id: 2, name: 'Team' },
{ id: 6, parent_id: 3, name: 'Support' },
{ id: 7, parent_id: 3, name: 'Sales' }
];
我们可以调用generateTree(flatArray)以获取以下树形菜单对象数组:
[
{
id: 1,
name: 'Home',
children: [
{
id: 2,
name: 'About',
children: [
{ id: 4, name: 'History', children: [] },
{ id: 5, name: 'Team', children: [] }
]
},
{
id: 3,
name: 'Contact',
children: [
{ id: 6, name: 'Support', children: [] },
{ id: 7, name: 'Sales', children: [] }
]
}
]
}
]
推荐文章
- thinkphp6 leftjoin联表查询时,子表有多条记录去重后获取子表的最新记录查询方法
- 前端报错:was loaded over HTTPS, but requested an insecure错误解决方案
- composer install常见错误解决方案 --ignore-platform-reqs解决版本冲突
- 82个常规的前端JavaScript方法封装(1~10)
- ref, toRef, toRefs,reactive, defineComponent, computed, unref, toRaw, watchEffect, onUpdated 10个VUE3前端API总结
- ThinkPHP6多条件搜索查询,表达式查询 FIND_IN_SET查询
- 国民APP微信内测新功能:朋友圈内容可转发给好友
- linux服务器定时任务crontab命令用法详解
- centos系统,宝塔面板SSL证书文件在哪里?
- JS检测移动设备环境:WeChat、Android、IOS

