这是我的数据:
[{
"id": 1,
"name": "item 1",
"group": "Group A"
}, {
"id": 2,
"name": "item 2",
"group": "Group A"
}, {
"id": 3,
"name": "item 3",
"group": "Group B"
}, {
"id": 4,
"name": "item 4",
"group": "Group B"
}, {
"id": 5,
"name": "item 5",
"group": "Group B"
}, {
"id": 6,
"name": "item 6",
"group": "Group C"
}]
Run Code Online (Sandbox Code Playgroud)
我想创建这样的表:
|======================|
|ID |NAME |
|======================|
|Group A |
|----------------------|
|1 |item 1 |
|2 |item 2 |
|======================|
|Group B |
|----------------------|
|3 |item 3 |
|4 |item 4 |
|5 |item 5 |
|======================|
|Group C |
|----------------------|
|6 |item 6 |
========================
Run Code Online (Sandbox Code Playgroud)
我尝试在每个循环中创建变量来存储“组”但不起作用,我可以在返回数据之前在服务器端进行分组,我仍然想在客户端进行分组,那么该怎么做呢?
Pan*_*kar 10
您可以使用以下逻辑来实现您的结果。
var groups = new Set(array.map(item => item.group)),
results = [];
groups.forEach(g =>
results.push({
name: g,
values: array.filter(i => i.group === g)
}
))
Run Code Online (Sandbox Code Playgroud)
HTML
<div *ngFor="let item in results">
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<ng-container>
<tr>
<td colspan="2">{{item.name}}</th>
</tr>
<tr *ngFor="let value in item.values">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
</tr>
</ng-container>
</table>
<div>
Run Code Online (Sandbox Code Playgroud)