Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Get to inside an array which is part of an object without a for loop, javascript

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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')

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!