You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tree.ts 2.3 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { DataNode } from 'antd/es/tree';
  2. import { parse } from 'querystring';
  3. /**
  4. * 构造树型结构数据
  5. * @param {*} data 数据源
  6. * @param {*} id id字段 默认 'id'
  7. * @param {*} parentId 父节点字段 默认 'parentId'
  8. * @param {*} children 孩子节点字段 默认 'children'
  9. */
  10. export function buildTreeData(
  11. data: any[],
  12. id: string,
  13. name: string,
  14. parentId: string,
  15. parentName: string,
  16. children: string,
  17. ) {
  18. const config = {
  19. id: id || 'id',
  20. name: name || 'name',
  21. parentId: parentId || 'parentId',
  22. parentName: parentName || 'parentName',
  23. childrenList: children || 'children',
  24. };
  25. const childrenListMap: any[] = [];
  26. const nodeIds: any[] = [];
  27. const tree: any[] = [];
  28. data.forEach((item) => {
  29. const d = item;
  30. const pId = d[config.parentId];
  31. if (!childrenListMap[pId]) {
  32. childrenListMap[pId] = [];
  33. }
  34. d.key = d[config.id];
  35. d.title = d[config.name];
  36. d.value = d[config.id];
  37. d[config.childrenList] = null;
  38. nodeIds[d[config.id]] = d;
  39. childrenListMap[pId].push(d);
  40. });
  41. data.forEach((item: any) => {
  42. const d = item;
  43. const pId = d[config.parentId];
  44. if (!nodeIds[pId]) {
  45. d[config.parentName] = '';
  46. tree.push(d);
  47. }
  48. });
  49. function adaptToChildrenList(item: any) {
  50. const o = item;
  51. if (childrenListMap[o[config.id]]) {
  52. if (!o[config.childrenList]) {
  53. o[config.childrenList] = [];
  54. }
  55. o[config.childrenList] = childrenListMap[o[config.id]];
  56. }
  57. if (o[config.childrenList]) {
  58. o[config.childrenList].forEach((child: any) => {
  59. const c = child;
  60. c[config.parentName] = o[config.name];
  61. adaptToChildrenList(c);
  62. });
  63. }
  64. }
  65. tree.forEach((t: any) => {
  66. adaptToChildrenList(t);
  67. });
  68. return tree;
  69. }
  70. export const getPageQuery = () => parse(window.location.href.split('?')[1]);
  71. export function formatTreeData(arrayList: any): DataNode[] {
  72. const treeSelectData: DataNode[] = arrayList.map((item: any) => {
  73. const node: DataNode = {
  74. id: item.id,
  75. title: item.label,
  76. key: `${item.id}`,
  77. value: item.id,
  78. } as DataNode;
  79. if (item.children) {
  80. node.children = formatTreeData(item.children);
  81. }
  82. return node;
  83. });
  84. return treeSelectData;
  85. }

No Description