【发布时间】:2020-06-17 06:34:50
【问题描述】:
我有这个应用程序,其中有 3 个搜索字段:用户名、组织和活动(布尔)。按下搜索按钮后,我将使用上述值的组合或单次搜索来过滤表格。
我的 Json:
[
{
"id": 1,
"userName": "abc",
"active": true,
"organisations": [{
"id": 2,
"organisation": "org1"
},
{
"id": 3,
"organisation": "org2"
}]
},
{
"id": 2,
"userName": "def",
"active": true,
"organisations": [{
"id": 4,
"organisation": "org4"
},
{
"id": 5,
"organisation": "org5"
}]
},
{
"id": 3,
"userName": "ghj",
"active": false,
"lastLogon": "",
"organisations": [{
"id": 6,
"organisation": "org6"
},
{
"id": 7,
"organisation": "org7"
}]
}
]
我的过滤器:
@Pipe({name: 'searchfilter'})
export class SearchFilterPipe implements PipeTransform {
transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
return items.filter(item => {
let notMatchingField = Object.keys(filter)
.find(key => item[key] !== filter[key]);
return !notMatchingField;
});
}
}
我的 HTML:
<tr *ngFor="let user of users | searchfilter: tableFilter;">
<td>{{ user.userName }}</td>
<td><input type="checkbox" [checked]="user.active"></td>
</tr>
tableFilter 是搜索对象,它可以有一个搜索字段或两个或三个字段的组合。例如:tableFilter = {"userName":"abc"} 或 tableFilter = {"userName":"abc", "active": true} 或 tableFilter = {"userName":"abc", "organisation:"org6", "active": true}。
我的代码适用于用户名或活动或两者。但是当我将组织用作单个字段或组合使用时,它会失败,因为我的数组是嵌套的。
因此,任何有关 Pipe 过滤器的帮助都会有所帮助。我听说过 Lodash 库,但我不知道如何使用它。提前致谢。
【问题讨论】:
-
"organisation:"org6" in your tableFilter 将不起作用。您正在将字符串与没有任何逻辑的数组进行比较。您需要额外的逻辑来查看数组
-
它适用于其他领域。但是由于组织是嵌套的,所以它失败了!
-
这能回答你的问题吗? Recursively filter array of objects
标签: javascript angular typescript ecmascript-6 lodash