How to check if an array contains a specific value?

-1

I have the following function:

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

It returns this:

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 example? The "role" const will be used in a comparison that accepts only the result in that particular format.

I'll 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 }
    ]
  }

At the moment, I'm only passing one function per user. However, I would like to leave the dynamic code in case any user has more than one function in the future.

    
asked by anonymous 20.08.2018 / 20:17

1 answer

0

Take out [0] .

So:

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

console.log(roles);

The [0] is getting you to get the first value of the array generated by map .

See my example:

const usuarios = [{nome: "Wallace"}, {nome: "Wayne"}]

console.log(usuarios.map( function (u) {
   return u.nome; 
}));

console.log(usuarios.map( function (u) {
   return u.nome; 
})[0]);
    
20.08.2018 / 20:22