let readings = {
"date" : "2017-07-09",
"reading" : [
{ "meal" : "Breakfast" },
{ "meal" : "Lunch" },
{ "meal" : "Dinner" },
{ "meal" : "Supper" }
]
}
{
"date" : "2017-07-10",
"reading" : [
{ "meal" : "Lunch" },
{ "meal" : "Dinner" },
{ "meal" : "Supper" }
]
}
{
"date" : "2017-07-11",
"reading" : [
{ "meal" : "Breakfast" },
{ "meal" : "Lunch" }
]
}
鉴于上述JSON
,是否有人可以建议最优雅的方式确保下表中的所有列排列?正如您所看到的,每餐都有一个列,但不是每个对象都包含每餐。
<table>
<thead>
<tr>
<th>Breakfast</th>
<th>Lunch</th>
<th>Dinner</th>
<th>Supper</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let reading of readings">
<td *ngFor="let item of reading.meal">Yes</td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
我认为如果不改变你的json就不能这样做。如果你愿意,可以尝试这种方式。将您的json更改为此格式。
{
"date" : "2017-07-10",
"reading" : {
"Lunch" : "meal_name",
"Dinner" : "meal_name",
"Supper" : "meal_name"
}
}
并将您的表格更改为此
<table>
<thead>
<tr>
<th>Breakfast</th>
<th>Lunch</th>
<th>Dinner</th>
<th>Supper</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let read of readings">
<td>{{ read.reading.Breakfast ? 'yes' : 'no'}}</td>
<td>{{ read.reading.Lunch ? 'yes' : 'no'}}</td>
<td>{{ read.reading.Dinner ? 'yes' : 'no'}}</td>
<td>{{ read.reading.Supper ? 'yes' : 'no'}}</td>
</tr>
</tbody>
</table>
我希望这会有所帮助:)
答案 1 :(得分:0)
感谢您的建议,伙计们。这是我使用的自定义管道。你觉得怎么样?
@Pipe({ name: 'readings' })
export class ReadingsPipe implements PipeTransform {
transform(readings: any): any {
return meals.map(meal => readings.find(reading => reading.meal === meal.meal));
}
}
let meals = [
{ "meal" : "Breakfast"},
{ "meal" : "Lunch" },
{ "meal" : "Dinner" },
{ "meal" : "Supper" }
];