Home > database >  Get to inside an array which is part of an object without a for loop, javascript
Get to inside an array which is part of an object without a for loop, javascript

Time:11-13

I have this code that works:

var roles = user.getRoles()
   for (var i = 0; i < roles.length; i  ){
      if (Roles[i].getName()== ‘Admin’){
        --gets to this line
   }
}

However I was wondering if I could get to a TRUE/FALSE without a for/if loop like the below that isn't working for me:

 if (user.getRoles().getName().indexOf('Admin') >-1){
    -does not get to this line
 }

Gives error: user.getRoles().getName is not a function

if I print out roles, the return is: UserRole@718816d, UserRole@1ae91200, UserRole@48baf10b, UserRole@777d6d90, UserRole@34ad99fb, UserRole@6606e47c, UserRole@79ab731e, UserRole@65269056, UserRole@3d9cbf48, UserRole@6ce88983, UserRole@4e792483, UserRole@1f8ca93a

CodePudding user response:

So what I guess from the provided information is that the method getName() is defined on the objects inside the roles array. So user.getRoles() returns you an array on which you cannot call getName() method

What I think you can do is user.getRoles().find(el => el.getName() === 'Admin')

CodePudding user response:

You could directly use Array operations findIndex or find. mdn docs

var roles = user.getRoles()
var i = roles.findIndex(r => r.getName() === 'Admin')
if(i > -1) {
    roles[i] // can access ith element
}

CodePudding user response:

It seems like using .includes should work for you in this situation. You appear to be searching for a known string ('Admin')

var roles = user.getRoles()
   if (roles.includes('Admin')) {
       - gets here if true
   }
}

https://www.digitalocean.com/community/tutorials/js-array-search-methods

CodePudding user response:

if(user.getRoles()?.find(role => role.getName() === 'admin')){
   // do stuff
}

The question mark is there to check if there is a value coming from getRoles.

Find will return null or the role.

  • Related