具有这样的数组(例如篮子中的产品)
[{
"name": "item 1",
"id": 1,
"price": 10
},
{
"name": "item 2",
"id": 2,
"price": 20
},
{
"name": "item 1",
"id": 1,
"price": 10
},
{
"name": "item 3",
"id": 3,
"price": 30
}]
如何在Angular 8中执行*ngFor
以便打印输出,如:
因此,基本上,我希望按名称(或ID)包装重复的商品,并只为它们显示一行。我还应该计算发生次数及其小计
答案 0 :(得分:4)
您可以在使用前预处理阵列。喜欢: Most efficient method to groupby on an array of objects
甚至更好-在管道中执行预处理并像这样使用它:
<div *ngFor="entry in items | customGroupByPype">
答案 1 :(得分:1)
尝试这样:
打字稿:
export class AppComponent {
originaldata = [{
"name": "item 1",
"id": 1,
"price": 10
},
{
"name": "item 2",
"id": 2,
"price": 20
},
{
"name": "item 1",
"id": 1,
"price": 10
},
{
"name": "item 3",
"id": 3,
"price": 30
}]
viewData = []
constructor() {
var groupedByData = this.groupByKey(this.originaldata, 'name')
(Object.keys(groupedByData)).forEach(x => {
this.viewData.push(
{
name:x,
quantity : groupedByData[x].length + 'x',
subtotal : (groupedByData[x].map(x=> x.price)).reduce(function(a, b) { return a + b; }, 0)
}
)
})
console.log(this.viewData)
}
groupByKey(data, key) {
return data.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
}
模板
<table>
<tr *ngFor="let item of viewData">
<td>{{item.quantity}}</td>
<td>{{item.name}}, </td>
<td>subtotal {{item.subtotal}}</td>
</tr>
</table>