/**
* mergeRowspan
* @param tableData: Record<string, string | number>[]
* @param config: { referenceValue: string, combineProp: string[] } referenceValue - 基准值 combineProp - 合并行的依据 基准值需为合并依据的第一项
* @returns tableData: any[]
*/
function mergeRowspan(tableData, config) {
if (!tableData.length) {
return tableData
}
// 读取配置
const { referenceValue, combineProp } = config
// 判断基准值是否存在 | 基准值是否tableData中数据的属性
if (!referenceValue || !tableData[0].hasOwnProperty(referenceValue)) {
return tableData
}
// 对tableData数据已基准值数据值进行分组格式化,以确保相同行相邻
const tableDataGroup = tableData.reduce((pre, current) => {
pre[current[referenceValue]] = pre[current[referenceValue]] || []
pre[current[referenceValue]].push(current)
return pre
}, {})
let list = []
for (const key in tableDataGroup) {
if (Object.hasOwnProperty.call(tableDataGroup, key)) {
const item = tableDataGroup[key];
list = [...list, ...item]
}
}
// rowspan 合并几行 colspan 合并后占用几列
combineProp.forEach((column, index) => {
// 记录合并项
let combineCount = 1
// 使用倒序遍历
for (let i = list.length - 1; i >= 0; i--) {
const curr = list[i]
const prev = list[i - 1]
if (i === 0) {
// 循环最后一次
curr[`${column}-span`] = {
rowspan: combineCount,
colspan: 1
}
break
}
if (prev[`${column}`] === curr[`${column}`]) {
++combineCount
curr[`${column}-span`] = {
rowspan: 0,
colspan: 0
}
} else {
curr[`${column}-span`] = {
rowspan: combineCount,
colspan: 1
}
// 前后项不相符时,对combinecount进行重置
combineCount = 1
}
}
})
return list
}
// 示例
var data = [{
id: '12987122',
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10
}, {
id: '12987122',
name: '王小虎',
amount1: '165',
amount2: '4.43',
amount3: 12
}, {
id: '12987122',
name: '王小虎',
amount1: '324',
amount2: '1.9',
amount3: 9
}, {
id: '12987125',
name: '王小虎',
amount1: '621',
amount2: '2.2',
amount3: 17
}, {
id: '12987126',
name: '王小虎',
amount1: '539',
amount2: '4.1',
amount3: 15
}]
var a = mergeRowspan(data, { referenceValue: 'id', combineProp: ['id', 'name'] })
console.log(a)
element表格行合并通用方法
于 2022-07-26 00:08:49 首次发布