25 lines
672 B
TypeScript
25 lines
672 B
TypeScript
export interface TreeNode<T=any> {
|
|||
|
|
key: string | number;
|
||
|
|
title: string;
|
||
|
|
children?: TreeNode<T>[];
|
||
|
|
raw?: T;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function buildTree<T extends { id: any; pId?: any; name?: string }>(list: T[]): TreeNode<T>[] {
|
||
|
|
const map = new Map<any, TreeNode<T>>();
|
||
|
|
const roots: TreeNode<T>[] = [];
|
||
|
|
list.forEach(item => {
|
||
|
|
map.set(item.id, { key: item.id, title: (item as any).title || item.name || String(item.id), raw: item, children: [] });
|
||
|
|
});
|
||
|
|
list.forEach(item => {
|
||
|
|
const node = map.get(item.id)!;
|
||
|
|
if (item.pId && map.has(item.pId)) {
|
||
|
|
map.get(item.pId)!.children!.push(node);
|
||
|
|
} else {
|
||
|
|
roots.push(node);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
return roots;
|
||
|
|
}
|
||
|
|
|