ReactJS如何遍历数组并在另一个数组中获取Object的特定属性

时间:2017-06-02 11:30:16

标签: javascript reactjs

所以我有一组与特定团队绑定的用户,每个用户都有特定的权限。如果用户与多个团队绑定,那么所有这些团队在阵列中也可用:

[
{
    "name" : "user1",
    "teams": [
        {"id": "123", "name": "team-1", "permissions" : 1}
    ]
},
{
    "name" : "user2",
    "teams": [
        {"id": "123", "name": "team-1", "permissions" : 3}
    ]
},
{
    "name" : "user3",
    "teams": [
        {"id": "456", "name": "team-2", "permissions" : 3},
        {"id": "789", "name": "team-3", "permissions" : 3},
        {"id": "123", "name": "team-1", "permissions" : 3},
        {"id": "233", "name": "team-4", "permissions" : 3}

    ]
}

]

所以现在我想要这个:

我获得了当前正在查看的团队的ID(ID:123),如何映射数组,以便我只能显示ID为123的团队的权限?

我做了以下操作,但这不起作用,因为User3的第一项是错误的团队。

 const MembersTable = observer(({ state }) => (
   <div>
     <table className="table table-hover table-responsive">
      <thead>
       <tr>
         <th>Name</th>
         <th>Email</th>
         <th>Permissions</th>
       </tr>
     </thead>
     <tbody>
      {state.accounts.map((account, i) => <MembersTableData state={state} account={account} team={account.teams} key={i}/>)}
     </tbody>
    </table>
 </div>
))

const MembersTableData = observer(({ state, account, organization }) => (
  <tr>
    <td>
      <span>{account.fullName}</span>
   </td>
    <td>{account.email}</td>
    <td>
     {team[0].permissions == 1 && <span>member</span>}
     {team[0].permissions == 2 && <span>administrator</span>}
     {team[0].permissions == 3 && <span>super admin</span>}
    </td>
  </tr>
 ))
在这种情况下,

this.state.team为“123”。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

team[0]将始终拥有用户所属的第一个团队。您想要的是具有id属性等于this.state.team的团队。因此,而不是team[0]尝试:

{team.find(t => t.id == this.state.team).permissions == 3 && <span>super admin</span>}

当然,这也适用于“会员”和“管理员”。

答案 1 :(得分:0)

你应该试试这个

const getTeamData = (data, teamId) => data.map(users => users.teams.filter(team => team.id === teamId )).reduce((acc, current) => acc.concat(current));

/**

[ {
  id: "123",
  name: "team-1",
  permissions: 1
}, {
  id: "123",
  name: "team-1",
  permissions: 3
}, {
  id: "123",
  name: "team-1",
  permissions: 3
}]
*/