1

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>

2
  • devices is an array. You have to access its elements by their index, like devices[0].mac_id. Are you trying to display all users? Then use *ngFor and only display selected properties of each user. You don't need any filters to do that. Commented Sep 27, 2019 at 23:04
  • I just want to display the User with the mac_id of "44:44:44:44:44". -Thanx for a prompt one Commented Sep 27, 2019 at 23:14

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.