angularangular-filters

Angular Custom Filters For Some Nested JSON Objects


I want to use an Angular filter for Users based on their MAC Address for devices they are currently using. I have some JSON data and my trial custom filter I need help with.

My Trial Custom filter:

  getCurrentUser(): User {
    return USERS.filter((user) => user.devices, mac_id == 44:44:44:44:44)[0];
  }

export const USERS: User[] = [
  {
    id: 1,
    email: 'yacie.qbi.com',
    pword: '123',
    fname: 'Tatenda Y',
    lname: 'Gatsi',
    date: '2012-10-16T17:57:28.556094Z',
    sa: 1,
    devices: [
      {
        mac_id: '33:33:33:33:33',
        imei: 91011,
        fone_no: 8888,
      }
    ]
  },
  {
    id: 2,
    email: 'chiko.qbi.com',
    pword: '123',
    fname: 'Tatenda Y',
    lname: 'Gatsi',
    date: '2015-09-16T02:00:28.015982Z',
    sa: 1,
    devices: [
      {
        mac_id: '44:44:44:44:44',
        imei: 91011,
        fone_no: 8888,
      }
    ]
  }
]

I expect to get results like: User ID and Mac_id in HTML like

  <mat-card *ngIf="user" fxFlex>
    <mat-card-content>
      <div>User ID: {{user.id}}</div>
      <div>Current MAC Address: {{user.devices.mac_id}}</div>
    </mat-card-content>
  </mat-card>


Solution

  • Based on additional info from comments, you want to display one user with mac_id of '44:44:44:44:44'.

    Your filter function isn't right. devices is an array and you aren't searching that array. You can use Array.some() to see if at least one device has given mac_id.

    getCurrentUser(): User { 
      // Only returning first user from filtered users.
      return USERS.filter(user => 
        user.devices.some(item => item.mac_id === '44:44:44:44:44'))[0];
    } 
    

    Then modify your HTML to display this user. devices[0] gives first device in devices array.

    <mat-card *ngIf="user" fxFlex>
      <mat-card-content>
        <div>User ID: {{user.id}}</div>
        <div>Current MAC Address: {{user.devices[0].mac_id}}</div>
      </mat-card-content>
    </mat-card>