【问题标题】:How to group data in Angular 2?如何在 Angular 2 中对数据进行分组?
【发布时间】:2016-09-11 22:16:06
【问题描述】:

如何使用 TypeScript 在 Angular 2 中对数据进行分组。我知道这是使用 Angular 1.X 中的“分组依据”过滤器完成的,但没有得到如何在 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, Cal. US", contactNumber: "+968754216984" },
            { id: 3, firstName: "Jamie", lastName: "King", department: 3, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },

            { id: 5, firstName: "Jacob", lastName: "Ridley", department: 5, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
            { id: 6, firstName: "Peter", lastName: "Parker", department: 3, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
            { id: 7, firstName: "Martin", lastName: "Luther", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
            { id: 8, firstName: "Raghav", lastName: "Kumar", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },

            { id: 9, firstName: "Narayan", lastName: "Sonmez", department: 3, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
            { id: 10, firstName: "Russell", lastName: "Andre", department: 2, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
            { id: 11, firstName: "Ramona", lastName: "King", department: 4, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
            { id: 12, firstName: "Andre", lastName: "Russell", department: 1, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" },

            { id: 13, firstName: "Nathan", lastName: "Leon", department: 1, age: 24, address: "24/7, Working hours apartment, Cal. US", contactNumber: "+968546215789" },
            { id: 14, firstName: "Brett", lastName: "Lee", department: 5, age: 25, address: "32-C, Happy apartments, Block-9C, Cal. US", contactNumber: "+968754216984" },
            { id: 15, firstName: "Tim", lastName: "Cook", department: 2, age: 32, address: "54/II, Glorydale apartment, Cal. US", contactNumber: "+967421896326" },
            { id: 16, firstName: "Steve", lastName: "Jobs", department: 5, age: 34, address: "51/C Shivalik, Cal. US", contactNumber: "+967842569842" }
        ];

我希望按部门统计员工人数,例如

部门 1 有 4 名员工

等等。

将部门 id 与实际部门连接起来(以便我可以得到部门名称)是我需要弄清楚的另一个故事。

【问题讨论】:

    标签: angular typescript1.7


    【解决方案1】:

    我会创建a custom pipe 来做到这一点,如下所述:

    @Pipe({name: 'groupBy'})
    export class GroupByPipe implements PipeTransform {
      transform(value: Array<any>, field: string): Array<any> {
        const groupedObj = value.reduce((prev, cur)=> {
          (prev[cur[field]] = 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>
    

    另见对应的plunkerhttps://plnkr.co/edit/49fWY1rMbSZtNQ3H

    【讨论】:

    • 感谢您的回复!我一定会试一试的。
    • 对我来说,这行 `return Object.keys(groupedObj).map(key => return { key, value: groupedObj[key] });` 行不通。我得到编译错误GroupByPipe.ts:20:65 ';' expected.你能帮忙吗
    • @yurzui 谢谢。我对你的回答做了一点改动。现在可以了。
    • 工作正常。如何在循环中获取数组的实际索引@yurzui
    • @Mubashir 我不知道你想获得哪个索引。它是分组数组。还要检查这个stackoverflow.com/questions/40340661/…
    【解决方案2】:

    如果您需要访问嵌套属性或需要比较对象,您可以这样做

    @Pipe({ name: 'groupByProperty' })
    export class GroupByPropertyPipe implements PipeTransform {
      transform(value: Array<any>, property: string): Array<any> {
        if (!value) {
          return null;
        }
        const group = value.reduce((previous, current) => {
          const parts = property.split('.');
          let currentValue: any;
          parts.forEach(part => {
            currentValue = currentValue ? currentValue[part] : current[part];
          });
          // Stringify objects for comparison
          currentValue = typeof currentValue === 'object' ? JSON.stringify(currentValue) : currentValue;
          if (!previous[currentValue]) {
            previous[currentValue] = [current];
          } else {
            previous[currentValue].push(current);
          }
          return previous;
        }, {});
        return Object.keys(group).map(key => ({ key, value: group[key] }));
      }
    }
    

    【讨论】:

      【解决方案3】:
      var dept = employees.map((m) => m.department).filter((f, i, ar) => ar.indexOf(f) === i);
      console.log(dept);
      
      var group = employees.reduce((accumulator, item, i, arr) => {
        if (dept.length) {
          var pop = dept.shift();
          var list = arr.filter((f) => f.department == pop);
          accumulator.push(...list);
        }
        return accumulator;
      }, []);
      
      console.log(group);
      

      【讨论】:

        【解决方案4】:

        你可以使用 ngx-pipes https://github.com/danrevah/ngx-pipes#groupby

        this.arrayObject = [
          {id: 1, elm: 'foo', value: 0}, 
          {id: 2, elm: 'bar', value: 1}, 
          {id: 3, elm: 'foo', value: 2}, 
          {id: 4, elm: 'foo', value: 2}
        ];
        
        this.arrayNestedObject = [
          {id: 1, prop: { deep: 'foo' }},
          {id: 2, prop: { deep: 'bar' }},
          {id: 3, prop: { deep: 'foo' }},
          {id: 4, prop: { deep: 'bar' }}
        ];
        <p>{{ arrayObject | groupBy: 'elm' }}</p> 
        <!-- Output: "{foo: [{id: 1, elm: 'foo', value: 0}, {id: 3, elm: 'foo', value: 2}, {id: 4, elm: 'foo', value: 2}], bar: [{id: 2, elm: 'bar', value: 1}]}" -->

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-16
          • 2013-01-25
          • 1970-01-01
          • 1970-01-01
          • 2021-07-14
          • 2022-01-13
          相关资源
          最近更新 更多