Search code examples
jsonangulartypescriptangular-pipe

Find and filter pipe for all content of Array as JSON format Angular 2


I have a search bar and I want to be able to search in all strings or columns of my received json or array of objects, with the pipe I wish to create. So I can be able to update this result in my table.

What I have until now of a Custom Pipe: (Doesn't do what I'm trying to)

transform(items: any[], args:string): any {
    let keys = [];
    for (let key in items) {
            keys.push({key: key, value: items[key]});
    }
    let ans = [];
    for (let k in keys){
        if(items[k].value.match('^.*' + args +'.*$')){
            ans.push({key: k, value: items[k]});
        }
    }
    return ans;  }   

Search HTML <input type="text" #filterInput (keyup)="0">

Loading in Table calling Pipe

<tbody *ngIf="usersBool">
<tr *ngFor="let entry of content | filterArrayOfObjects: filterInput" >
    <td>{{entry.value.enrollmentId}}</td>
    <td>{{entry.value.firstName}}</td>
    <td>{{entry.value.LastName}}</td>
    <td>{{entry.value.typeOfUser}}</td>
    <td>edit</td>
    <td>delete</td>

</tr>
</tbody>

I've got dummy content called as:

this.content = [
               {
                   "enrollmentId": "A0xxxxxx",
                   "firstName": "Bob",
                   "LastName": "Bob",
                   "typeOfUser": 'Admin'
               },
               {
                   "enrollmentId": "A0xxxxxx",
                   "firstName": "Bob",
                   "LastName": "Bob",
                   "typeOfUser": 'Admin'
               },
               {
                   "enrollmentId": "A0xxxxxx",
                   "firstName": "Bob",
                   "LastName": "Bob",
                   "typeOfUser": 'Admin'
               }
           ];

Solution

  • So I had to consider each key I have in my content Dictionary and analyze if any in their content match with what I input in my search bar

    transform(items: any[], args:string): any {
    
        let ans = [];
        for (let k in items){
            if(items[k].enrollmentId.match('^.*' + args +'.*$')
               || items[k].firstName.match('^.*' + args +'.*$')
               || items[k].lastName.match('^.*' + args +'.*$')
               || items[k].typeOfUser.match('^.*' + args +'.*$')) {
                ans.push({key: k, value: items[k]});
            }
        }
        return ans;
    

    }