需求:根据后端返回的数据,把数据相同的单元格进行合并,如图所示
技术:angular框架+ng-zorro组件中table表格
代码:
html中:(这段代码是前三列的代码,是需要判断相同数据合并的)
<tr *ngFor="let item of table02 let allIndex = index;">
<ng-container *ngFor="let t of mergeColumns; index as i">
<ng-container *ngIf="item[t]!==undefined ">
<!-- 方案2 -->
<td colspan="4" [attr.rowspan]="item[mergeFix+t]">{{ item[t] }}
</td>
<!-- 方案2 -->
</ng-container>
</ng-container>
</tr>
ts中:
//tableData是数据
tableData: any;
//table02是html所需要的数组
table02: any = [];
mergeFix = 'mergeFlag'
// mergeColumns 是需要判断相同数据的字段
mergeColumns = ['specName', 'deviceName', 'dataPointName'];
rowspan: any;
ngOnInit(): void {
if (this.data) {
this.table02 = this.sortAndMerge(this.data)
}
}
// 数据相同合并单元格
private sortAndMerge(rawDataList): any[] {
const rowspan = this.mergeFix, mergeColumns = this.mergeColumns;
if (rawDataList.length > 1) {//长度⼤于1才有资格进⼀步处理
const sortColumn = Object.keys(rawDataList[0]),
keySort = raw => {
for (let i = raw.length - 1; i > 0; i--) {
let newObj = {}, tmpObj = raw[i];
sortColumn.forEach(s => newObj[s] = tmpObj[s]);
raw[i] = newObj;
}
return raw;
}, compare = (a, b, c = sortColumn[0], i = 0) => {
if (a[c] === b[c]) { //等于的话进⾏判断是否还有后续字段需要排序,没有则返回0;有则递归进⾏后续字段排序处理。
if (i === sortColumn.length - 1) {//没有后续字段
return i = 0;
}
i++;
return compare(a, b, sortColumn[i], i);//递归排序后续字段
} else if (a[c] > b[c]) { //⼤于返回1
return 1;
} else { //⼩于返回-1
return -1;
}
}, arr = keySort(JSON.parse(JSON.stringify(rawDataList))).sort(compare), aLen = arr.length
for (let i = mergeColumns.length - 1; i >= 0; i--) {//先迭代待合并列
let index = 0;
let title = mergeColumns[i];
let span = 1;//合并列属性默认为1
for (let j = 0; j < aLen; j++) {
let comp = arr[index][title];
if (arr[j][title] === comp) {
j !== index && (delete arr[j][title], span++);
j === aLen - 1 && (arr[index][rowspan + title] = span);
} else {
span > 1 && (arr[index][rowspan + title] = span, span = 1);
index = j
}
}
}
return arr
}
return rawDataList
}