interface Tree { id: number resourceUrl: string type: string fileName: string defaultSort: number children?: Tree[] } interface OriginDataItem { id: number resourceUrl: string fileName: string type: string defaultSort: number parentId?: number } export const originData: OriginDataItem[] = [ { id: 12, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 10, defaultSort: 2 }, { id: 78, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 77, defaultSort: 1 }, { id: 80, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 78, defaultSort: 4 }, { id: 82, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 81, defaultSort: 1 }, { id: 84, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 83, defaultSort: 1 }, { id: 86, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 85, defaultSort: 1 }, { id: 88, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 87, defaultSort: 1 }, { id: 90, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 89, defaultSort: 1 }, { id: 92, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 91, defaultSort: 1 }, { id: 94, resourceUrl: 'bbb', type: 'image', fileName: '张三', parentId: 93, defaultSort: 1 } ] /** * 将 originData 转换为 dataSource 的树形结构 * @param data 原始数据数组 * @returns 转换后的树形结构数据 */ export function transformToTreeData(data: OriginDataItem[]): Tree[] { // 创建映射表,用于快速查找 const itemMap = new Map() const result: Tree[] = [] // 首先创建所有节点 data.forEach((item) => { itemMap.set(item.id, { id: item.id, resourceUrl: item.resourceUrl, type: item.type, fileName: item.fileName, defaultSort: item.defaultSort, children: [] }) }) // 构建树形结构 data.forEach((item) => { const treeNode = itemMap.get(item.id)! if (item.parentId) { const parentNode = itemMap.get(item.parentId) if (parentNode) { parentNode.children!.push(treeNode) } else { // 如果找不到父节点,作为根节点处理 result.push(treeNode) } } else { // 没有父节点,作为根节点 result.push(treeNode) } }) // 递归排序函数 function sortChildren(node: Tree) { if (node.children && node.children.length > 0) { // 重新排列 children node.children = node.children.sort((a, b) => a.defaultSort - b.defaultSort) // 递归处理子节点 node.children.forEach((child) => sortChildren(child)) } } // 重新排列根节点 const sortedResult = result.sort((a, b) => a.defaultSort - b.defaultSort) // 递归排序所有子节点 sortedResult.forEach((node) => sortChildren(node)) return sortedResult } // 使用示例 export const transformedDataSource = ref(transformToTreeData(originData))