【发布时间】:2019-10-16 12:23:40
【问题描述】:
import {
Pipe,
PipeTransform
} from '@angular/core';
/*
* Group an array by a property (key)
* Usage:
* value | groupBy : 'field'
*/
@Pipe({
name: 'groupBy'
})
export class GroupByPipe implements PipeTransform {
transform(value: Array < any > , field: string): Array < any > {
// prevents the application from breaking if the array of objects doesn't exist yet
if (!value) {
return null;
}
const groupedObj = value.reduce((previousVal, currentVal) => {
if (!previousVal[currentVal[field]]) {
previousVal[currentVal[field]] = [currentVal];
} else {
previousVal[currentVal[field]].push(currentVal);
}
return previousVal;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedObj).map(key => ({
key,
value: groupedObj[key]
}));
}
}
我已经实现了一个自定义 groupBy 管道,但它只适用于一个简单的对象字符串,例如当我传递这样的东西时它可以工作:
console.log(new GroupByPipe().transform(this.selectedServices, 'name'));
但我想传递一些更复杂的东西:
console.log(new GroupByPipe().transform(this.selectedServices,'paymentCycle.name'));
如何让这个管道接受更复杂的 groupBy,例如:
console.log(new GroupByPipe().transform(this.selectedServices, 'paymentCycle.name'));
【问题讨论】:
-
您有什么理由恢复编辑以使您的帖子更难理解?
-
请see this answer 并尝试在您的代码中调整它。