检查嵌套数组reactjs中是否存在对象

时间:2020-06-02 07:52:32

标签: javascript reactjs

我有以下数据集:

人:

person: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,
        
                  ]
            }

我想做的是根据该用户是否有权限进行一些条件渲染。

             { this.passtest()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }

然后将调用this.passtest()方法,该方法将包含用于检查用户是否具有我所需要的权限的逻辑:

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      // Not sure what logic I can put here to return true as long as the permission 'codename' field tallies 
     });

    return passing
  }

将感谢您的帮助!谢谢!

3 个答案:

答案 0 :(得分:1)

passtest(codeName){
    return !!this.props.person.groups.find(group => group.permissions.find(permission => permission.codename === codeName));
}

使用:

{ 
  this.passtest('can_edit')?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}

对于代号数组:

passtest(codeNames){
  return codeNames.every(
    codeName => !!this.props.person.groups.find(
      group => group.permissions.find(
        permission => permission.codeName === codeName
      )
    )
  )
}

使用:

{ 
  this.passtest(['can_edit', 'can_write'])?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}

答案 1 :(得分:0)

这取决于您要寻找的权限。如果您正在寻找任何东西,可以这样做:

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      return group.permission // this will true if permission array is > 0
     });

    return passing
  }

或者如果您正在寻找更具体的内容

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      if  (group.permissions[0].id === 1) {
         return true
      }
      return false
     });

    return passing
  }

您可以更改以下行:if(group.permissions[0].id === 1)以匹配您想要的任何权限

下面编辑

如果您将权限更改为这样的结构,则应该可以使用:

permissions : {codename: 'codename'}

答案 2 :(得分:0)

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      group.permissions.forEach((permission) => {
        // do a check in here for each permission
        if (permission.codename === 'can_edit') {
            return true
        }
      })
      return false
     });

    return passing
  }