How to check if an array contains a specific value?

I have the following function:

const role: string = tokenPayload.params.role.map(r => {
  return r.value;
}) [0];

It returns the following result:

author

If I remove the index [0], it returns this:

["author", "admin"]

Is it possible for the function to return all values in the same format as the first exemple?

The const "role" will be used in a comparison === that only accepts result in that specific format. I will put the full function for better understanding:

canActivateChild(route: ActivatedRouteSnapshot): boolean {
    const helper = new JwtHelperService();
    const expectedRole = route.data.expectedRole;
    const token = this.authService.getToken();
    const tokenPayload = helper.decodeToken(token);
    const role: string = tokenPayload.params.role.map(r => {
  return r.value;
}) [0];
console.log(role);
if (!this.authService.isAuthenticated() || role !== expectedRole) {
  this.router.navigate(['/admin']);
  return false;
}
return true;
}

router component:

{
    path: 'container-users',
    component: ContainerUsersComponent,
    canActivateChild: [AuthGuard],
    data: {
      expectedRole: 'admin'
    },
    children: [
      { path: '', component: ListUsersComponent },
      { path: 'list-users', component: ListUsersComponent },
      { path: 'form-new-user', component: FormNewUserComponent }
    ]
  }

Upvotes: 1

Views: 9232

Answers (2)

Benjamin Scholtz
Benjamin Scholtz

Reputation: 823

Instead of taking the first element of the array generated by map, use the string array and check if it contains the expectedRole string:

roles = tokenPayload.params.role.map(r => {
  return r.value;
});

// Use the following function
(roles.indexOf(expectedRole) == -1);

// Instead of this
role !== expectedRole;

See How to find if an array contains a specific string in JavaScript? - this explains how to check if an array of values contains a single value.

Upvotes: 0

tdragon
tdragon

Reputation: 3329

It seems the user in your application can have multiple roles and what you are trying to do is checking whether any of these roles attached to the user is expectedRole. expectedRole is a single string value, while roles attached to the user are represented by the array of some objects, where the role name is stored in value property, so you cannot use === operator, you should use a method like indexOf(), some() or includes() to verify user has expectedRole assigned.

So, instead of selecting all role names with map function, I would directly check the required role:

const hasExpectedRole = tokenPayload.params.role.some(r => r.value === expectedRole)

and later, in if statement

if (... || !hasExpectedRole)

Upvotes: 5

Related Questions