在Angular上使用lodash过滤对象数组

时间:2019-05-15 14:41:32

标签: angular filter nested lodash

我在Angular 7上工作,我想对从后端收到的对象列表应用几个过滤器。 这些对象属于我称为“ CV”的类型。 CV内部还有其他对象,如下所述。

CV {
  employee: Employee;
  certifications: Certification[];
}
Employee {
  empId: number;
  empAgency: string;
  empBu: string;
}

我的主要问题是我需要根据嵌套对象的属性过滤CV列表。

本教程启发我运用多个过滤器:https://angularfirebase.com/lessons/multi-property-data-filtering-with-firebase-and-angular-4/

我在typeScript中尝试了类似的方法。

  employees: CV[];
  filteredEmployees: CV[];
  //array I use to filter
  filters = {};
  
  //properties I wanna filter by
  empAgency: string;
  empBu: string;
  //standard entry to delete a filter property value
  private DefaultChoice: string = "DefaultChoice";
  
   private applyFilters() {
    if (this.filteredEmployees.length === this.employees.length) {
      this.filteredEmployees = _.filter(this.filteredEmployees,     _.conforms(this.filters));
    } else {
      this.filteredEmployees = this.employees;
      this.filteredEmployees = _.filter(this.filteredEmployees, _.conforms(this.filters));
    }
  }
filterExact(property: string, property2: string, rule: any) {
    if (rule ==='DefaultChoice') {
      delete this.filters[property][property2];
      this.filters[property] = [];
      this.filters[property][property2] = null;
    }
    else {
      this.filters[property] = [];
      this.filters[property][property2] = val => val === rule;
    }
    this.applyFilters();
  }

但是它不适用于嵌套属性。我的问题是我不了解如何将嵌套对象的属性正确地传递给函数。

有人可以帮忙吗?

在帮助下,我还提供了有关如何在Angular中的嵌套对象上链接多个过滤器(带有/不带有破折号)的任何其他建议。我仍然是这个领域的新手,请随时向我指出正确的方向!

1 个答案:

答案 0 :(得分:0)

按照您链接的示例,我认为您不需要将两个属性都传递给filterExact()。我认为您只需要编写其他过滤器功能即可执行您要完成的第二级过滤:

  filterExactAgency(property: string, rule: any) {
    this.filters[property] = val => val == rule
    this.applyFilters()
  }

  filterExactBusinessUnit(property: string, rule: any) {
    this.filters[property] = val => val == rule
    this.applyFilters()
  }