Typescript : Check if object exist in array by value

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"));


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


I got this solution for you: check this out

export class RoleComponent implements OnInit {
  roles: Role[] = [];
  isRoleExist:boolean = false;
  constructor() { }

  ngOnInit() {
    const data = this.getRoles();
    this.roles = JSON.parse(data);

    this.isRoleExist = this.checkRoleExistence('PILOTE');
    console.log(this.isRoleExist);
  }

  checkRoleExistence(roleLabel: string):boolean {
    return this.roles.some(r => r.roleLabel === roleLabel);
  }

  getRoles() {
    return `[
    {"roleId": "69801", "roleLabel": "ADMIN"},
    {"roleId": "69806", "roleLabel": "SUPER_ADMIN"},
    {"roleId": "69805", "roleLabel": "RB"},
    {"roleId": "69804", "roleLabel": "PILOTE"},
    {"roleId": "69808", "roleLabel": "VENDEUR"},
    {"roleId": "69807", "roleLabel": "SUPER_RB"}
    ]`;
  }
}

export class Role {
  roleId: number;
  roleLabel: string;
}