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(新的GroupByPipe()。transform(this.selectedServices,'name'));
但是我想通过这样更复杂的事情:
console.log(新的GroupByPipe()。transform(this.selectedServices,'paymentCycle.name'));
我已经实现了一个自定义的groupBy管道,但它仅适用于简单的对象字符串。
如何使此管道接受更复杂的groupBy,例如:
console.log(新的GroupByPipe()。transform(this.selectedServices,'paymentCycle.name'));
从'@ angular / core'导入{Pipe,PipeTransform}; / * *按属性(键)对数组进行分组*用法:*值| groupBy:'field'* / @Pipe({name:'groupBy'})导出类...
我建议不要自己实施groupBy。使用lodash groupBy,它可以满足您的搜索需求。