角度:按属性名称分组,如果重复则仅显示一个

时间:2019-09-11 13:39:19

标签: javascript angular filter group-by

具有这样的数组(例如篮子中的产品)

[{
    "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以便打印输出,如:

  • 2个项目1,小计20个
  • 1x项2,小计20
  • 1x项目3,小计30

因此,基本上,我希望按名称(或ID)包装重复的商品,并只为它们显示一行。我还应该计算发生次数及其小计

2 个答案:

答案 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>

请参见Stackbiltz Demo