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

时间:2019-05-10 08:30:06

标签: json angular typescript group-by angular-pipe

我使用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" }
];

我想按颜色对列表进行排序,并按prices来获得color的总和。

这就是我想要得到的:

[
    {
        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" }
        ]
    }
];

我开始用color对列表进行StackBlitz排序,但是我不能求和。如果有人愿意帮助我。

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] }));
  }
}

谢谢。

1 个答案:

答案 0 :(得分:2)

在return语句中,您可以添加sum语句:

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使其起作用,但最好在源数据中使用这些值数字