antd实现动态表头,以及表格的合并
拿到的数据结构
const data=[
{
"Month": "202101",
"WMeterType": "--",
"Cycle": "1",
"UserCount": 44342,
"subsets": [
{
"Name": "0",
"Value": "334462"
},
{
"Name": "15",
"Value": "203557"
},
{
"Name": "20",
"Value": "10040"
},
{
"Name": "25",
"Value": "4011"
},
{
"Name": "32",
"Value": ""
},
{
"Name": "40",
"Value": "469"
},
{
"Name": "50",
"Value": "6"
},
{
"Name": "65",
"Value": ""
},
{
"Name": "100",
"Value": ""
},
{
"Name": "150",
"Value": ""
},
{
"Name": "总计",
"Value": "552545"
},
{
"Name": "实际抄见",
"Value": "552635"
}
]
},
]
对数据进行处理
//
const arr = data.map((v,index) => {
const obj = {
meterMonth: v.Month,
readType: v.WMeterType,
meterPeriodcycle: v.Cycle,
relativeNum: v.UserCount,
key:index,
};
const obj2 = {};
v.subsets.map((w) => {
obj2[w.Name] = w.Value;
});
return { ...obj, ...obj2 };
});
表头数据
//subsets这个数组,是data中每一项都含有的,并且每一项中subsets的Name都是一样的,所以我们只需要取一组数据
const dt = data[0].subsets;
const ww = arr;
const columns = [
{
title: "水表类型",
dataIndex: "readType",
key: "readType",
align: "center",
//处理列表的合并
render: (value, row, index) => {
let rowSpan = 1;
let arrIndex = 0;
ww.forEach((item, Dindex) => {
if (item.key === row.key) {
arrIndex = Dindex;// 先获取readType所在的arr的Dindex
}
});
if (index === 0) { // 当值在多个页面出现时重新记录rowSpan
ww.forEach((item, Dindex) => {
if (Dindex > arrIndex) {
if (item.readType === row.readType) {
rowSpan += 1;
}
}
});
} else if (ww[arrIndex].readType === ww[arrIndex - 1].readType) {
rowSpan = 0;
} else {
ww.forEach((item, Dindex) => {
if (Dindex > arrIndex) {
if (item.readType === row.readType) {
rowSpan += 1;
}
}
});
}
return {
children: row.readType,
props: {
rowSpan,
},
};
},
},
{
title: "水表周期",
dataIndex: "meterPeriodcycle",
key: "meterPeriodcycle",
align: "center",
},
{
title: "起抄月份",
dataIndex: "meterMonth",
key: "meterMonth",
align: "center",
},
{
title: "计费计量用水量-机械表(m³)",
//动态表头
children: dt.map((v) => ({
title: v.Name,
dataIndex: v.Name,
align: "center",
})),
},
{
title: "相关户数",
dataIndex: "relativeNum",
key: "relativeNum",
align: "center",
},
];
参考连接:https://blog.csdn.net/qq_33472885/article/details/99679327