【发布时间】:2019-10-02 18:08:40
【问题描述】:
我在 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 中的嵌套对象上链接多个过滤器的任何其他建议(带/不带 lodash)。我还是这个领域的新手,所以请随时为我指明好的方向!
【问题讨论】:
-
您应该在stackblitz.com 上提供您的问题的minimal reproducible example,以便人们可以帮助您。现在阅读您的问题让我意识到这很难处理,有很多无用的信息或业务信息我们不会用来回答您。
-
为什么使用下划线而不是 typescript 的默认数组 filter() ?
-
@trichetriche 感谢您的建议。我对 Stackoverflow 也很陌生,所以我不知道我需要在 stackblitz 上发帖,我会尽快做的。但是我不会说我的例子很冗长,真实的代码要大得多,对象要复杂得多。我想清楚地说明我的思维过程,以及我如何拥有一个有效的实际代码,以及在什么时候它不再有效。
-
@Stavm 因为从我收集的内容来看,使用 filter() 链接过滤器意味着一定的顺序:你应用第一个,你的地图结果,你应用第二个等等。在我的情况下,我想要一个可以应用的完全可逆的过滤器堆栈。我想从哪个过滤器开始,如果我回到我的默认值,则取消过滤器属性。但是,如果您认为使用 filter() 更容易,请指点我一个解决方案?
标签: angular filter nested lodash