GroupByWithSumPipe 对列表进行排序并对分组项目的属性求和 Angular

GroupByWithSumPipe to sort a list and sum an attribute of grouped items Angular

我使用 GroupBy 管道根据参数对数据进行分组并且效果很好,但我想向该管道添加第二个参数,如下所示:

<li *ngFor="let object of myArray | groupByWithSum:'color':'price'">
    COLOR:{{object.key}} - SUM_PRICE:{{object.sum}}
</li>

允许根据对象属性分组的所有项目的总和,这里是 price.

示例: StackBlitz HERE

这是我的对象列表:

var myArray = [
    { name: "Apple",    color: "Green",     price: "5,999" },
    { name: "Banana",   color: "Yellow",    price: "6,999" },
    { name: "Grape",    color: "Green",     price: "12,999" },
    { name: "Melon",    color: "Yellow",    price: "10,999" },
    { name: "Orange",   color: "Orange",    price: "3,999" }
];

我想按颜色对这个列表进行排序,并通过 color 得到 prices 的总和。

这就是我想要得到的:

[
    {
        key: "Green",
        sum: "18,998‬",
        value: [
            { name: "Apple", color: "Green", price: "5,999" },
            { name: "Grape", color: "Green", price: "12,999" }
        ]
    },
    {
        key: "Yellow",
        sum: "17,998",
        value: [
            { name: "Banana", color: "Yellow", price: "6,999" },
            { name: "Melon",  color: "Yellow", price: "10,999" }
        ]
    },
    {
        key: "Orange",
        sum: "3,999",
        value: [
            { name: "Orange", color: "Orange", price: "3,999" }
        ]
    }
];

我开始 StackBlitzcolor 对列表进行排序,但我无法求和。如果有人愿意帮助我。

GroupByWithSumPipe:

export class GroupByWithSumPipe implements PipeTransform {
  transform(collection: object[], property: string, sum: string): object[] {
    // prevents the application from breaking if the array of objects doesn't exist yet
    if(!collection) { return null; }

    const groupedCollection = collection.reduce((previous, current)=> {
      if(!previous[current[property]]) {
          previous[current[property]] = [current];
      } else {
          previous[current[property]].push(current);
      }

      return previous;
    }, {});

    // this will return an array of objects, each object containing a group of objects
    return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
  }
}

提前谢谢你。

在您的 return 语句中,您可以添加求和语句:

transform(collection: object[], property: string, sum: string): object[] {
  //...

  return Object.keys(groupedCollection).map(key => ({ 
    key, 
    sum: groupedCollection[key].reduce((a, b) => a + parseInt(b[sum]), 0),
    value: groupedCollection[key]
  }));
}

example

虽然您使用的是价格字符串,但我添加了一个 parseInt 以使其正常工作,但您最好只在源数据中输入这些数值