源数据:
let menuList = [
{
id: 1,
title: "菜单1",
parent: 0,
},
{
id: 2,
title: "菜单2",
parent: 0,
},
{
id: 3,
title: "菜单1-1",
parent: 1,
},
{
id: 4,
title: "菜单1-2",
parent: 1,
},
{
id: 5,
title: "菜单2-1",
parent: 2,
},
{
id: 6,
title: "菜单3",
parent: 0,
},
];
期望数据结构:
[{
"id": 1,
"title": "菜单1",
"parent": 0,
"children": [{
"id": 3,
"title": "菜单1-1",
"parent": 1
}, {
"id": 4,
"title": "菜单1-2",
"parent": 1
}]
}, {
"id": 2,
"title": "菜单2",
"parent": 0,
"children": [{
"id": 5,
"title": "菜单2-1",
"parent": 2
}]
}, {
"id": 6,
"title": "菜单3",
"parent": 0
}]
实现方式:
let menuList = [
{
id: 1,
title: "菜单1",
parent: 0,
},
{
id: 2,
title: "菜单2",
parent: 0,
},
{
id: 3,
title: "菜单1-1",
parent: 1,
},
{
id: 4,
title: "菜单1-2",
parent: 1,
},
{
id: 5,
title: "菜单2-1",
parent: 2,
},
{
id: 6,
title: "菜单3",
parent: 0,
},
];
function getTreeList(list, id, treeList) {
// 先找出最顶层的数据 parent 父级为0 的数据
for (let item of list) {
if (item.parent == id) {
treeList.push(item);
}
}
//找出子集
for (let item of treeList) {
item.children = [];
getTreeList(list, item.id, item.children);
if (item.children.length == 0) {
delete item.children; // 删除children 长度为0 的
}
}
return treeList;
}
let res = getTreeList(menuList, 0, []);
console.log(JSON.stringify(res));