平级数组
const array = [
{ id: 1, name: '菜单1', icon: 'icon-shouye', route: null, parent_id: null },
{ id: 3, name: '菜单1-1', icon: null, route: '/home', parent_id: 1 },
{ id: 4, name: '菜单1-2', icon: null, route: '/home', parent_id: 1 },
{ id: 5, name: '菜单2', icon: null, route: '/system', parent_id: null },
{ id: 6, name: '菜单1-3', icon: null, route: '/system', parent_id: 1 },
{ id: 7, name: '系统1-3-1', icon: null, route: '/system', parent_id: 6 },
{ id: 8, name: '系统1-1-1', icon: null, route: '/system', parent_id: 3 }
];
第一种方式
function buildTree(array, parentId = null) {
const tree = [];
for (const item of array) {
if (item.parent_id === parentId) {
const children = buildTree(array, item.id);
if (children.length > 0) {
item.children = children;
}
tree.push(item);
}
}
return tree;
}
buildTree(array)
第二种方式
function buildTree(array) {
const treeMap = {}; // 哈希映射,用于快速查找节点
const tree = [];
// 第一次遍历,将节点按照id作为键存储到哈希映射中
for (const item of array) {
item.children = [];
treeMap[item.id] = item;
}
// 第二次遍历,构建树形结构
for (const item of array) {
if (item.parent_id !== null) {
const parent = treeMap[item.parent_id];
if (parent) {
parent.children.push(item);
}
} else {
tree.push(item);
}
}
return tree;
}
buildTree(array)