Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : Check if object exist in array by value

I have this data:

roles = [
{roleId: "69801", role: "ADMIN"}
{roleId: "69806", role: "SUPER_ADMIN"}
{roleId: "69805", role: "RB"}
{roleId: "69804", role: "PILOTE"}
{roleId: "69808", role: "VENDEUR"}
{roleId: "69807", role: "SUPER_RB"}
]

i have to filter my table to check if there is an object containing a specifie value of role .

My function should look like this :

checkRoleExistence(role){

// if role exists on one of the objects return true
// else returne false
}

to use it i would do s.th like this :

let ifExists = this.checkRoleExistence("PILOTE") ;

I would like to use the "filter" function of Ecmascript .

Suggestions ?

like image 234
firasKoubaa Avatar asked Feb 15 '26 22:02

firasKoubaa


2 Answers

You can use some method and destructuring.

let roles = [ {roleId: "69801", role: "ADMIN"}, {roleId: "69806", role: "SUPER_ADMIN"}, {roleId: "69805", role: "RB"}, {roleId: "69804", role: "PILOTE"}, {roleId: "69808", role: "VENDEUR"}, {roleId: "69807", role: "SUPER_RB"} ]

const checkRoleExistence = roleParam => roles.some( ({role}) => role == roleParam)

console.log(checkRoleExistence("ADMIN"));
console.log(checkRoleExistence("RA"));
console.log(checkRoleExistence("RB"));
like image 187
Mihai Alexandru-Ionut Avatar answered Feb 18 '26 10:02

Mihai Alexandru-Ionut


a little addition to all the answers given here. You can use find() to get value which matches your requirement.

const index = this.roles.findIndex(role=> role.name === 'ADMIN'); if (index >-1) { const value= this.roles[index].roleId); }

this will give you roleId , where it matches your query

like image 45
Sujay Avatar answered Feb 18 '26 11:02

Sujay



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!