Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if a role exist in array in js?

I have saved roles of an user in an array in db. The roles array looks like this.

{
    "_id" : ObjectId("5708a54c8becc5b357ad82bb"),
    "__v" : 2,
    "active" : true,
    "adminReports" : [],
    "created" : ISODate("2016-04-09T06:46:36.814Z"),
    "displayName" : "Admin Local",
    "email" : "[email protected]",
    "firstName" : "Admin",
    "groups" : [],
    "lastLogin" : ISODate("2016-12-29T13:34:48.592Z"),
    "lastName" : "Local",
    "password" : "jYQB4vNsJLkkSveGZygN3llMMHbNkZWnnQZuaV4l0NAoOixh2JndlNFojigHz4Sus5St8loOWaKeKTtPVDwY4Q==",
    "profileImageURL" : "modules/users/client/img/profile/default.png",
    "provider" : "local",
    "roles" : [ 
        "superAdmin", "admin","manager","user"
    ],
    "salt" : "1v/XyKlUdhNqgEBPaAPSeA==",
    "userWeeklyReport" : true,
    "username" : "admin"
}

When i have to check if logged in user is manager or admin then I am checking it with indexOf which is the right way to do it but my code does not looks good. Here is a snippet if i have to check if logged in user is either admin, CEO or manager.

if(req.user.roles.indexOf('admin') !== -1 || req.user.roles.indexOf('manager') !== -1 || req.user.roles.indexOf('CEO') !== -1){
    //some code goes here
}

There is a lot of indexOf and it doesn't looks good. Can anyone tell me what is the right way to do it, so that my code looks more readable.T Thanks in advance.

like image 745
Manish Saraan Avatar asked Dec 14 '25 10:12

Manish Saraan


1 Answers

You can use array#some to check if a role which is stored in an array exist in your req.user.roles. array#includes will check if the selected role exist in the req.user.roles.

if(['admin','manager','CEO'].some(role => req.user.roles.includes(role)))
like image 124
Hassan Imam Avatar answered Dec 15 '25 22:12

Hassan Imam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!