我需要创建一个包含Json对象数组信息的表。 假设数据以下列格式到达。
profiles = [{
id: 1,
userId:1000,
profile: "Cars 2018",
parentId: 0,
created: "00.00.0000 00:00:00",
fields: [
{id:1, type:"text", name: "Brand"},
{id:2, type:"decimal", name: "velocity"},
{id:3, type:"int", name: "leather"}
],
data: [
{ id:1, value:'BMW 2018', profileId:1, fieldId:1 },
{ id:2, value:'130 Km/h', profileId:1, fieldId:2 },
{ id:3, value:'Yes', profileId:1, fieldId:3 },
{ id:4, value:'Mercedez Benz 2018', profileId:1, fieldId:1 },
{ id:5, value:'180 Km/h', profileId:1, fieldId:2 },
{ id:6, value:'No', profileId:1, fieldId:3 }
]
}];
到目前为止一切都很简单,我可以这样做,然后去......
<div *ngFor="let field of profiles">
<table>
<thead>
<tr>
<th *ngFor="let link of field.fields">
{{ link.name }}
</th>
</tr>
</thead>
<tbody>
<tr>
<td *ngFor="let dt of field.data">
{{ dt.value }}
</td>
</tr>
</tbody>
</table>
</div>
但结果将是:
Brand | Velocity | Leather |
BMW 2018 | 130 Km/h | Yes | Mercedez Benz 2018 | 130 Km/h | No
如何使数据适应列数?
UPDATE -------- 我添加了&#39; fieldId&#39;数据,所以数据应显示在对应的字段中......
答案 0 :(得分:0)
您应该在代码中修改数据,以便它实际上是您想要显示的内容。你可以很容易地使用数组映射运算符:
profiles = profiles.map(profile => {
profile.data = profile.data.filter(d => !!profile.fields.find(f => f.id === d.id));
return profile;
});
您不希望在模板中尝试此逻辑,因为模板逻辑应尽可能干净简单。您的工具/功能在代码中要大得多。
如果这是通过一个observable来实现的,你可以在rx map operator
中使用数组映射运算符答案 1 :(得分:0)
只需操作组件类中的数据。
试试这个
let profiles = [{
id: 1,
userId:1000,
profile: "Cars 2018",
parentId: 0,
created: "00.00.0000 00:00:00",
fields: [
{id:1, type:"text", name: "Brand"},
{id:2, type:"decimal", name: "velocity"},
{id:3, type:"int", name: "leather"}
],
data: [
{ id:1, value:'BMW 2018', profileId:1 },
{ id:2, value:'130 Km/h', profileId:1 },
{ id:3, value:'Yes', profileId:1 },
{ id:4, value:'Mercedez Benz 2018', profileId:1 },
{ id:5, value:'180 Km/h', profileId:1 },
{ id:6, value:'No', profileId:1 }
]
}];
//Create a buffer for current data
let dataTable = profiles;
let index = 0;
for(let x of profiles){
//Create a data container
let data = [];
//Number of iterations base on the header
let iterations = x.data.length / x.fields.length;
for(let r = 0; r < iterations; r++){
data.push(dataTable[index].data.splice(0, x.fields.length));
}
//Equate it since array are mutable
x.data = data;
index++;
}
然后在你的html文件中这样做
<div *ngFor="let field of profiles">
<table>
<thead>
<tr>
<th *ngFor="let link of field.fields">
{{ link.name }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let dt of field.data">
<td *ngFor="let y of dt">
{{ y.value }}
</td>
</tr>
</tbody>
</table>