场景:需要展示每个学生每个月的平均分数,月份不固定,后台返回多少月就展示多少月,如下图。
以JeecgBoot低代码为例,假设后台返回的数据格式是这样的:
const list = [
{
id: '111',
name: 'Joy',
scoreList: [
{ subject: '一月', score: 88 },
{ subject: '二月', score: 100 },
{ subject: '三月', score: 99 },
{ subject: '四月', score: 99 },
{ subject: '五月', score: 99 },
],
},
{
id: '222',
name: 'Grace',
scoreList: [
{ subject: '一月', score: 96 },
{ subject: '二月', score: 96 },
{ subject: '三月', score: 100 },
{ subject: '四月', score: 99 },
{ subject: '五月', score: 99 },
],
},
{
id: '333',
name: 'Nancy',
scoreList: [
{ subject: '一月', score: 94 },
{ subject: '二月', score: 72 },
{ subject: '三月', score: 82 },
{ subject: '四月', score: 99 },
{ subject: '五月', score: 99 },
],
},
];
template部分:
<BasicTable @register="registerTable" :loading="loading" :dataSource="dataSource"></BasicTable>
具体实现:
const dataSource = ref<Array<any>>([]); // 列表数据
// 固定列
const column: BasicColumn[] = [
{
title: '姓名',
dataIndex: 'name',
},
];
// 首先获取动态列
const dynamicColumns =
list[0]?.scoreList?.map((item) => {
return {
title: item.subject,
dataIndex: item.subject,
};
}) || [];
// 固定列和动态列合并,设置表头
setColumns([...column, ...dynamicColumns]);
// 转换获取到的后台数据格式即可
dataSource.value = list?.map((item) => {
const newObj = {
name: item.name,
};
item?.scoreList?.forEach((subItem) => {
newObj[subItem.subject] = subItem.score;
});
return newObj;
});