【问题标题】:Angular: How to use a groupBy Pipe in arrayAngular:如何在数组中使用 groupBy Pipe
【发布时间】: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 并尝试在您的代码中调整它。

标签: angular pipe


【解决方案1】:

我建议不要自己实现 groupBy。请改用 lodash groupBy,它可以满足您的搜索需求。

    const data = [
      { foo: { name: "A", id: "1" } },
      { foo: { name: "B", id: "1" } },
      { foo: { name: "A", id: "2" }}
    ];

    console.log(_.groupBy(data, 'foo.name')); // import * as _ from 'lodash';

(见https://lodash.com/docs/4.17.15#groupBy

结果

{A: Array(2), B: Array(1)}
A: Array(2)
0: {foo: {…}}
1: {foo: {…}}
length: 2
__proto__: Array(0)
B: Array(1)
0: {foo: {…}}
length: 1
__proto__: Array(0)
__proto__: Object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 2020-08-24
    • 2022-11-21
    • 1970-01-01
    • 2018-12-07
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多