如何在Angular 2中对数据进行分组?

前端之家收集整理的这篇文章主要介绍了如何在Angular 2中对数据进行分组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用TypeScript将Angular 2中的数据分组.我知道这是使用Angular 1.X中的“group by”过滤器完成的,但没有得到如何在Angular 2中对数据进行分组.我有这个数组:
import {Employee} from './employee';
        export var employees: Employee[];
        employees = [
            { id: 1,firstName: "John",lastName: "Sonmez",department: 1,age: 24,address: "24/7,Working hours apartment,Cal. US",contactNumber: "+968546215789" },{ id: 2,firstName: "Mark",lastName: "Seaman",department: 2,age: 25,address: "32-C,Happy apartments,Block-9C,contactNumber: "+968754216984" },{ id: 3,firstName: "Jamie",lastName: "King",department: 3,age: 32,address: "54/II,Glorydale apartment,contactNumber: "+967421896326" },{ id: 5,firstName: "Jacob",lastName: "Ridley",department: 5,{ id: 6,firstName: "Peter",lastName: "Parker",{ id: 7,firstName: "Martin",lastName: "Luther",department: 4,{ id: 8,firstName: "Raghav",lastName: "Kumar",age: 34,address: "51/C Shivalik,contactNumber: "+967842569842" },{ id: 9,firstName: "Narayan",{ id: 10,firstName: "Russell",lastName: "Andre",{ id: 11,firstName: "Ramona",{ id: 12,firstName: "Andre",lastName: "Russell",{ id: 13,firstName: "Nathan",lastName: "Leon",{ id: 14,firstName: "Brett",lastName: "Lee",{ id: 15,firstName: "Tim",lastName: "Cook",{ id: 16,firstName: "Steve",lastName: "Jobs",contactNumber: "+967842569842" }
        ];

我希望按部门统计员工,比如

Department 1 has 4 employees

等等.

将部门ID与实际部门联系起来(以便我可以获得部门名称)是我需要弄清楚的另一个故事.

您可以使用 custom pipe执行此操作,如下所述:
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
  transform(value: Array<any>,field: string): Array<any> {
    const groupedObj = value.reduce((prev,cur)=> {
      if(!prev[cur[field]]) {
        prev[cur[field]] = [cur];
      } else {
        prev[cur[field]].push(cur);
      }
      return prev;
    },{});
    return Object.keys(groupedObj).map(key => ({ key,value: groupedObj[key] }));
  }
}

然后在您的模板上,您可以写:

<div *ngFor="let item of employees | groupBy:'department'">
  Department {{ item.key }} has {{ item.value.length }} employees
</div>

另见相应的plunker https://plnkr.co/edit/cLnlH13IH4WAsuRdol4n?p=preview

希望它能帮到你!

原文链接:https://www.f2er.com/angularjs/143937.html

猜你在找的Angularjs相关文章