ST80
ST80

Reputation: 3903

ReactJS How to loop through an array and fetch specific attribute of Object inside another array

So I have an array of users which are tied to specific teams, each user with specific permissions. If the user is tied to multiple teams, all these teams are available too in the array:

[
{
    "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}

    ]
}

]

so now I want this:

I got the ID of the current Team I'm looking at (ID: 123), how can I map the array, so that I can display only the permissions for the team with the ID: 123?

I did the following, but that doesnt work, since the first Item of User3 is the wrong team.

 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 is "123" in this case.

How can I solve this?

Upvotes: 0

Views: 49

Answers (2)

Alejandro Nanez
Alejandro Nanez

Reputation: 345

You should try this

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
}]
*/

Upvotes: 0

Freeman Lambda
Freeman Lambda

Reputation: 3675

team[0] will always have the first team that the user is part of. What you want is the team that has an id property that equals this.state.team. Thus, instead of team[0] try doing:

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

Of course this goes for "member" and "admin" as well.

Upvotes: 1

Related Questions