我有以下数据结构,
[{
date: '23-09-2024',
location: [{
locationName: 'London',
locationID: '12',
ticketIds: [19299298,7383883,585885]
},
{
locationName: 'USA',
locationID: '11',
ticketIds: [1224298,73855553,5555585]
}]
},{
date: '24-09-2024',
location: [{
locationName: 'London',
locationID: '12',
ticketIds: [19299298,7383883,585885]
},
{
locationName: 'USA',
locationID: '11',
ticketIds: [124748898,7385444453,5555585]
}]
}]
我必须按如下方式迭代表中的数据,
我的实施:
代码:
<table>
<tr *ngFor="let date of toRunData">
<th>Dates</th>
<th>{{date.date}}</th>
<th *ngFor="let loc of date.location">
<td>{{loc.name}}</td>
<td>{{loc.ticketIds.length}}</td>
</th>
</tr>
</table>
我知道代码中存在错误,因为我现在正在学习状态,但任何人都可以帮助我纠正上述代码以获得预期的结果。谢谢!!
要获取所需的格式,您可以按照以下方法操作。请记住,这是一种方法,您也有可能找到其他方法。这是此方法的 Stackblitz 演示。
以上数组不得更改初始日期的顺序,如 特定日期的票数应具有相同的索引 位于第一个数组中。
上述内容可以通过以下代码实现。
<table>
<tr>
<th>Dates</th>
<th *ngFor="let date of dates">{{date}}</th>
</tr>
<tr *ngFor="let loc of locations">
<td>{{loc.locationName}}</td>
<td *ngFor="let avl of loc.availability">
Tickets Avl: {{avl}}
</td>
</tr>
</table>
在您的
ts
文件中使用以下代码:
export class TableComponent implements OnInit {
toRunData = [
{
date: '23-09-2024',
location: [
{
locationName: 'London',
locationID: '12',
ticketIds: [19299298, 7383883, 585885, 5858856],
},
{
locationName: 'USA',
locationID: '11',
ticketIds: [1224298, 73855553, 5555585],
},
],
},
{
date: '24-09-2024',
location: [
{
locationName: 'London',
locationID: '12',
ticketIds: [19299298, 7383883, 585885],
},
{
locationName: 'USA',
locationID: '11',
ticketIds: [124748898, 7385444453, 5555585],
},
],
},
];
locations: any[] = [];
ngOnInit() {
this.toRunData.map((date) =>
date.location.forEach((loc: any) => {
if (!loc.availability) {
loc.availability = [];
}
const ind = this.locations.findIndex(
(lo) => loc.locationID === lo.locationID
);
loc.availability.push(loc.ticketIds.length);
if (ind === -1) {
this.locations.push(loc);
} else {
this.locations[ind].availability.push(loc.ticketIds.length);
}
})
);
}
get dates() {
return this.toRunData.map((date) => date.date);
}
}