如何用PrimeNG p-table实现行列转换的动态数据绑定?
问题描述
我有如下JSON数据,希望使用PrimeNG的p-table将其呈现为指定的行列转换后的表格格式,但当前实现出现行重复问题,无法按预期绑定数据。
数据如下:
[ { "Year": 2023, "InputData": { "OilProduction": 0, "GasProduction": 0, "NGLProduction": 0 } }, { "Year": 2024, "InputData": { "OilProduction": 1, "GasProduction": 2, "NGLProduction": 3 } } ]
期望的表格布局:
| 参数 | 2023 | 2024 |
|---|---|---|
| oil production | 0 | 1 |
| gas production | 0 | 2 |
| NGL production | 0 | 3 |
解决方案
完全可以通过p-table实现这个需求,核心是先转换数据结构,将原数据从「按年份分组」转为「按参数分组」,再结合p-table的模板渲染即可解决行重复问题。
1. 数据转换(组件逻辑)
在组件类中添加数据转换方法,把原数组转成适合表格渲染的结构:
// 原数据 originalData = [ { Year: 2023, InputData: { OilProduction: 0, GasProduction: 0, NGLProduction: 0, }, }, { Year: 2024, InputData: { OilProduction: 1, GasProduction: 2, NGLProduction: 3, }, }, ]; // 转换后的数据 tableData: any[]; ngOnInit() { // 提取所有参数名 const parameters = Object.keys(this.originalData[0].InputData); // 构建表格数据 this.tableData = parameters.map(param => { const row = { parameter: param.replace(/([A-Z])/g, ' $1').toLowerCase().replace(/^./, str => str.toUpperCase()) }; // 为每个年份添加对应参数值 this.originalData.forEach(item => { row[item.Year] = item.InputData[param]; }); return row; }); }
2. p-table模板实现
在模板中使用p-table绑定转换后的数据,动态生成年份列:
<p-table [value]="tableData"> <ng-template pTemplate="header"> <tr> <th>parameter</th> <!-- 动态渲染年份列 --> <th *ngFor="let year of originalData.map(item => item.Year)">{{ year }}</th> </tr> </ng-template> <ng-template pTemplate="body" let-row> <tr> <td>{{ row.parameter }}</td> <!-- 动态渲染对应年份的参数值 --> <td *ngFor="let year of originalData.map(item => item.Year)">{{ row[year] }}</td> </tr> </ng-template> </p-table>
关键说明
- 数据转换后,每一行对应一个参数,列对应各个年份,完美匹配期望布局
- 动态生成年份列的写法,能兼容后续新增年份的情况,无需修改模板
- 行重复问题的根源是原实现直接遍历原年份数据导致重复渲染,转换数据后每个参数仅对应一行,自然解决重复问题
内容的提问来源于stack exchange,提问作者s d
相关产品推荐
相关产品推荐

