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