我使用 GroupBy
管道根据参数对数据进行分组,效果非常好,但我想向该管道添加第二个参数,如下所示:
<li *ngFor="let object of myArray | groupByWithSum:'color':'price'">
COLOR:{{object.key}} - SUM_PRICE:{{object.sum}}
</li>
允许根据对象属性分组的所有项目的总和,此处为价格
。
示例: 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" }
];
我想按颜色对此列表进行排序,并按颜色
获取价格
的总和。
这就是我想要得到的:
[
{
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" }
]
}
];
我启动了 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] }));
}
}
提前谢谢您。
最佳答案
在您的返回声明中,您可以添加总和声明:
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]
}));
}
虽然您使用字符串表示价格,但我添加了一个 parseInt
来使其工作,但您最好在源数据中添加这些数值
关于json - GroupByWithSumPipe 对列表进行排序并对分组项的属性求和 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073613/