一、显示菜单:使用树形结构分组,把数据a变成数据b
let a= {
"data": [
{ id: 1, title: "menu1", parentId: 0 },
{ id: 2, title: "menu2", parentId: 0 },
{ id: 3, title: "menu1_1", parentId: 1 },
{ id: 4, title: "menu1_2", parentId: 1 },
{ id: 5, title: "menu2_1", parentId: 2 },
],
"message": "操作成功",
"code": 200
}
let b=[
{
"id": 1,
"title": "menu1",
"parentId": 0,
"children": [
{
"id": 3,
"title": "menu1_1",
"parentId": 1,
"children": []
},
{
"id": 4,
"title": "menu1_2",
"parentId": 1,
"children": []
}
]
},
{
"id": 2,
"title": "menu2",
"parentId": 0,
"children": [
{
"id": 5,
"title": "menu2_1",
"parentId": 2,
"children": []
}
]
}
]
1、方法一:使用递归
function buildTree(items, parentId = 0) {
return items
.filter(item => item.parentId === parentId)
.map(item => ({
...item,
children: buildTree(items, item.id)
}));
}
// 使用示例
const flatData = [
{ id: 1, title: "menu1", parentId: 0 },
{ id: 2, title: "menu2", parentId: 0 },
{ id: 3, title: "menu1_1", parentId: 1 },
{ id: 4, title: "menu1_2", parentId: 1 },
{ id: 5, title: "menu2_1", parentId: 2 },
];
const treeData = buildTree(flatData);
console.log(treeData);
2、方法二:使用 reduce 和对象引用
function buildTreeWithReduce(items) {
const itemMap = {};
const tree = [];
// 首先创建所有项的映射
items.forEach(item => {
itemMap[item.id] = { ...item, children: [] };
});
// 构建树结构
items.forEach(item => {
if (item.parentId === 0) {
tree.push(itemMap[item.id]);
} else {
if (itemMap[item.parentId]) {
itemMap[item.parentId].children.push(itemMap[item.id]);
}
}
});
return tree;
}
const treeData = buildTreeWithReduce(flatData);
console.log(treeData);
3、方法三:使用 Map 对象(ES6)
function buildTreeWithMap(items) {
const map = new Map();
const tree = [];
items.forEach(item => {
map.set(item.id, { ...item, children: [] });
});
for (const item of map.values()) {
if (item.parentId === 0) {
tree.push(item);
} else {
const parent = map.get(item.parentId);
if (parent) {
parent.children.push(item);
}
}
}
return tree;
}
const treeData = buildTreeWithMap(flatData);
console.log(treeData);