遍历初始数据,建立一个以id为key的Map。
创建一个根节点数组,遍历初始数据,根据parentId将数据放入对应的父节点下。
递归遍历构建树结构。
以下是一个使用JavaScript的示例代码:
[
{ "id": 1, "name": "Root", "parentId": null, "order": 1 },
{ "id": 2, "name": "Child1", "parentId": 1, "order": 1 },
{ "id": 3, "name": "Child2", "parentId": 1, "order": 2 },
{ "id": 4, "name": "Grandchild1", "parentId": 2, "order": 1 },
{ "id": 5, "name": "Grandchild2", "parentId": 2, "order": 2 },
{ "id": 6, "name": "Child3", "parentId": 1, "order": 3 }
]
function buildTree(data, parentId) {
let tree = [];
if (!parentId) {
tree = data.filter(node => !node.parentId);
} else {
tree = data.filter(node => node.parentId === parentId);
}
tree.sort((a, b) => a.order - b.order); // 按照order字段排序
tree.forEach(node => {
node.children = buildTree(data, node.id);
});
return tree;
}
// 使用示例
const flatData = [
{ "id": 1, "name": "Root", "parentId": null, "order": 1 },
{ "id": 2, "name": "Child1", "parentId": 1, "order": 1 },
{ "id": 3, "name": "Child2", "parentId": 1, "order": 2 },
{ "id": 4, "name": "Grandchild1", "parentId": 2, "order": 1 },
{ "id": 5, "name": "Grandchild2", "parentId": 2, "order": 2 },
{ "id": 6, "name": "Child3", "parentId": 1, "order": 3 }
];
const treeData = buildTree(flatData, null);
console.log(treeData);