給我一個typescript 數組轉樹的方法
以下是一个 TypeScript 的数组转树的方法:
interface TreeNode {
id: number;
parentId: number;
children?: TreeNode[];
}
function arrayToTree(arr: TreeNode[]): TreeNode[] {
const map: { [key: number]: TreeNode } = {};
const roots: TreeNode[] = [];
arr.forEach((node) => {
map[node.id] = { ...node, children: [] };
});
arr.forEach((node) => {
const parent = map[node.parentId];
if (parent) {
parent.children?.push(map[node.id]);
} else {
roots.push(map[node.id]);
}
});
return roots;
}
使用示例:
const arr = [
{ id: 1, parentId: 0 },
{ id: 2, parentId: 1 },
{ id: 3, parentId: 1 },
{ id: 4, parentId: 2 },
{ id: 5, parentId: 2 },
{ id: 6, parentId: 3 },
];
const tree = arrayToTree(arr);
console.log(tree);
输出结果:
[
{
"id": 1,
"parentId": 0,
"children": [
{
"id": 2,
"parentId": 1,
"children": [
{
"id": 4,
"parentId": 2,
"children": []
},
{
"id": 5,
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"parentId": 1,
"children": [
{
"id": 6,
"parentId": 3,
"children": []
}
]
}
]
}
]
``
原文地址: http://www.cveoy.top/t/topic/hXH9 著作权归作者所有。请勿转载和采集!