element表格的行列动态合并
elementUI表格的行和列进行动态合并
本次需求是,根据后端返回的动态数据,实现表格的行与列的动态合并

直接粘代码吧
const processDataForMerge = (rawData: TableDataItem[]): TableDataItem[] => {if (!rawData || rawData.length === 0) return []// 优化分组逻辑,使用Map提高查找效率const customerGroups = new Map<string, Map<string, TableDataItem[]>>()// 对数据进行分组rawData.forEach((item) => {const customerKey = item.customerNameconst directionKey = item.saleDirectionNameif (!customerGroups.has(customerKey)) {customerGroups.set(customerKey, new Map())}const directionMap = customerGroups.get(customerKey)!if (!directionMap.has(directionKey)) {directionMap.set(directionKey, [])}directionMap.get(directionKey)!.push(item)})// 构建带小计的数据结构const finalData: TableDataItem[] = []// 遍历客户分组let directionTypeLen = 0let customerNameItem = ''let loopIndex = 0 // 添加外部计数器来跟踪循环次数customerGroups.forEach((directionMap, customerName) => {let customerItemCount = 0 // 记录客户下的实际数据项数量(不包括小计)let customerTotalItems = 0 // 预计算客户下所有数据项数量// 每次循环后递增计数器if (loopIndex === 1) {customerNameItem = customerName}loopIndex++// 预计算客户下的总数据项数,避免嵌套循环directionMap.forEach((items) => {directionTypeLen++customerTotalItems += items.length})// 遍历销售方向分组directionMap.forEach((directionData, directionKey) => {// 使用 reduce 一次性计算汇总数据const { totalWeight, totalVehicles, totalAmount } = directionData.reduce((acc, item) => ({totalWeight: acc.totalWeight + (item.totalWeight || 0),totalVehicles: acc.totalVehicles + (item.totalVehicles || 0),totalAmount: acc.totalAmount + (item.totalAmount || 0)}),{ totalWeight: 0, totalVehicles: 0, totalAmount: 0 })// 添加每个明细行directionData.forEach((item, index) => {// 初始化行合并信息item.customerRowSpan = 0item.directionRowSpan = 0// 对于客户名称列,只在客户的第一个销售方向的第一个数据项设置行合并if (customerItemCount === 0) {item.customerRowSpan = directionTypeLen + customerTotalItems}// 对于销售方向列,每个销售方向的第一个数据项设置行合并if (index === 0 && !item.isSubtotal) {item.directionRowSpan = directionData.length + 1}finalData.push(item)customerItemCount++})// 添加销售方向小计行,使用专门的函数创建finalData.push(createSubtotalRow('direction', {weight: Number(totalWeight.toFixed(2)),vehicles: totalVehicles,amount: Number(totalAmount.toFixed(2))}))})})// 确保序号列连续显示,使用 map 更简洁let currentIndex = 1return finalData.map((item) => ({ ...item, index: currentIndex++ }))
}
var foo = 'bar';
