Typescript:按值检查对象是否存在于数组中

时间:2018-07-24 12:16:33

标签: javascript angular typescript ecmascript-6 filtering

我有此数据:

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"}
]

我必须过滤我的表以检查是否存在包含角色指定值的对象。

我的功能应如下所示:

checkRoleExistence(role){

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

要使用它,我会像这样:

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

我想使用 Ecmascript “过滤器” 功能。

建议?

3 个答案:

答案 0 :(得分:9)

您可以使用some方法和解构

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

答案 1 :(得分:1)

这里给出的所有答案都有一点补充。您可以使用find()获取符合您要求的值。

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

这将为您提供roleId,它与您的查询匹配

答案 2 :(得分:0)

我为您提供了以下解决方案: 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;
}