Within my application, there are 3 search fields available: username, organisation, and active status (boolean). When the search button is pressed, a table is filtered using a combination of these values or by a single search query.
The Json data structure:
[
{
"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"
}]
}
]
The Filter logic:
@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;
});
}
}
The Html implementation:
<tr *ngFor="let user of users | searchfilter: tableFilter;">
<td>{{ user.userName }}</td>
<td><input type="checkbox" [checked]="user.active"></td>
</tr>
The tableFilter object allows for a single search field or a combination of two or three fields. For example: tableFilter = {"userName":"abc"} or tableFilter = {"userName":"abc", "active": true} or tableFilter = {"userName":"abc", "organisation:"org6", "active": true}.
While my code successfully filters based on username, active status, or both, it encounters issues when attempting to filter by organisation due to the nested array structure.
Any assistance with optimizing the Pipe filter functionality would be greatly appreciated. I have heard of the library Lodash but am unsure how to integrate it into my code. Thank you in advance.