TreeUtils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * 树形工具类
  3. */
  4. export default class TreeUtils {
  5. public static CHILDREN = 'children';
  6. public static HAS_CHILD = 'hasChild';
  7. public static HAS_PARENT = 'hasParent';
  8. /**
  9. * 将list转为tree
  10. * @param list 列表数据
  11. * @param keyGetter
  12. * @param parentKeyGetter
  13. * @param topParentCode 顶级节点的parentId
  14. */
  15. public static convertList2Tree<T>(
  16. list: T[],
  17. keyGetter: (T) => string | number,
  18. parentKeyGetter: (T) => string | number,
  19. topParentCode?: string | number,
  20. ): T[] | null {
  21. if (list == null) {
  22. return null;
  23. }
  24. if (topParentCode === undefined || topParentCode === null) {
  25. topParentCode = '0';
  26. }
  27. const treeList: any[] = [];
  28. for (const value of list) {
  29. const parentId = parentKeyGetter(value);
  30. // 如果父ID 等于顶级父ID,则是顶级节点
  31. if (parentId === null || parentId === topParentCode) {
  32. treeList.push(value);
  33. continue;
  34. }
  35. for (const parent of list) {
  36. const id = keyGetter(parent);
  37. if (id === parentId) {
  38. if (!parent[this.CHILDREN]) {
  39. parent[this.CHILDREN] = [];
  40. }
  41. parent[this.CHILDREN].push(value);
  42. // 设置节点含有下级
  43. parent[this.HAS_CHILD] = true;
  44. // 设置节点含有上级
  45. value[this.HAS_PARENT] = true;
  46. }
  47. }
  48. }
  49. return treeList;
  50. }
  51. }