Home > Back-end >  Filter and display using id from object if matching criteria
Filter and display using id from object if matching criteria

Time:10-11

I have an array of objects from a database and I'm looking to filter the results if they match the correct criteria. (i.e if a user's id matches the correct id of the page then display the results for that user).

TS -

  async getResultsForId() {
    const resultsFromDB = await this.backendService.getResults();
    const serviceUserId = resultsFromDB.serviceUserId;
    if (serviceUserId === '1234567890') {
      resultsFromDB.filter(item => {
        return item.serviceUserId;
      });
    }

HTML -

<ngx-datatable-column name="Reason" prop="reason" [minWidth]="100">
        <ng-template ngx-datatable-cell-template let-rowIndex="rowIndex" let-value="value" let-row="row">
         <div >
           <span> {{row.reasonType}} </span>
         </div>
          <div  *ngIf="row.reasonDescription !== 'None'">
            <span > {{row.reasonDescription}} </span>
          </div>
        </ng-template>
 </ngx-datatable-column>

I have logged the results, but for example in this case I only want to display results that have the serviceUserId of '1234567890'

I have logged the results, but for example in this case I only want to display results that have the serviceUserId of '1234567890'

CodePudding user response:

I would suggest you use the .filter method and check if the values of your serviceUserId matches your string. So for example:

async getResultsForId() {
    const resultsFromDB = await this.backendService.getResults();
    const serviceUserId = resultsFromDB.serviceUserId;
    const filterdResult = this.resultsFromDB.filter(result: any => result.serviceUserId === serviceUserId);
    return filterdResult;
}

CodePudding user response:

Try using forEach

async getResultsForId() {
    const resultsFromDB = await this.backendService.getResults();
    const serviceUserId = resultsFromDB.serviceUserId;
    this.resultsFromDB.forEach((object:any)=>{
          if( serviceUserId === '1234567890'){
            console.log(object)
          }
  • Related