oa_based/src/utils/list2tree.util.ts

82 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-02-28 08:32:35 +08:00
export type TreeNode<T = any> = T & {
2024-02-28 17:02:46 +08:00
id: number;
parentId: number;
children?: TreeNode<T>[];
};
2024-02-28 08:32:35 +08:00
export type ListNode<T extends object = any> = T & {
2024-02-28 17:02:46 +08:00
id: number;
parentId: number;
};
2024-02-28 08:32:35 +08:00
export function list2Tree<T extends ListNode[]>(
items: T,
2024-02-28 17:02:46 +08:00
parentId: number | null = null
2024-02-28 08:32:35 +08:00
): TreeNode<T[number]>[] {
return items
.filter(item => item.parentId === parentId)
2024-02-28 17:02:46 +08:00
.map(item => {
const children = list2Tree(items, item.id);
2024-02-28 08:32:35 +08:00
return {
...item,
...(children.length ? { children } : null),
2024-02-28 17:02:46 +08:00
};
});
2024-02-28 08:32:35 +08:00
}
/**
*
* @param treeData
* @param key
* @param value
* @returns
*/
export function filterTree2List(treeData, key, value) {
const filterChildrenTree = (resTree, treeItem) => {
if (treeItem[key].includes(value)) {
2024-02-28 17:02:46 +08:00
resTree.push(treeItem);
return resTree;
2024-02-28 08:32:35 +08:00
}
if (Array.isArray(treeItem.children)) {
2024-02-28 17:02:46 +08:00
const children = treeItem.children.reduce(filterChildrenTree, []);
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
const data = { ...treeItem, children };
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
if (children.length) resTree.push({ ...data });
2024-02-28 08:32:35 +08:00
}
2024-02-28 17:02:46 +08:00
return resTree;
};
return treeData.reduce(filterChildrenTree, []);
2024-02-28 08:32:35 +08:00
}
/**
*
* @param treeData
* @param predicate
* @returns
*/
export function filterTree<T extends TreeNode>(
treeData: TreeNode<T>[],
2024-02-28 17:02:46 +08:00
predicate: (data: T) => boolean
2024-02-28 08:32:35 +08:00
): TreeNode<T>[] {
function filter(treeData: TreeNode<T>[]): TreeNode<T>[] {
2024-02-28 17:02:46 +08:00
if (!treeData?.length) return treeData;
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
return treeData.filter(data => {
if (!predicate(data)) return false;
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
data.children = filter(data.children);
return true;
});
2024-02-28 08:32:35 +08:00
}
2024-02-28 17:02:46 +08:00
return filter(treeData) || [];
2024-02-28 08:32:35 +08:00
}
export function deleteEmptyChildren(arr: any) {
2024-02-28 17:02:46 +08:00
arr?.forEach(node => {
if (node.children?.length === 0) delete node.children;
else deleteEmptyChildren(node.children);
});
2024-02-28 08:32:35 +08:00
}