Reputation: 17
I am new to JSX and I am trying to get the number of Employees for each team this.state.teams[0].employee.length
will give me the number of employee for the [0]
object in the array, how can I get the number of employees for each Team and only render it once?
render() {
const {teams, isLoading} = this.state;
const { location } = this.props;
if (isLoading) {
return <p>Loading...</p>;
}
// console.log("Number of Employees team", this.state.teams[0].employee.length);
const teamList = teams.map(team => {
console.log("TEAM Employees", teams[0].employee.length);
return <tr key={team.id}>
<td>
<div className="tableContent">
<div>
{team.name}
</div>
<div>
<ul>{team.employee.map(employee => {
return <li key={employee.id}>{employee.name}: {employee.email}</li>
})}</ul>
</div>
<div>
{team.employee.map(employee => {
return <li key={employee.id}>{teams[0].employee.length}</li>
})}
</div>
</div>
</td>
</tr>
});
Upvotes: 1
Views: 715
Reputation: 2573
You can use Object.keys(teams[0].employee).length
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. MDN
Upvotes: 0
Reputation: 98
You can try this for a specific team:
const teamList = teams.map(team => {
console.log("TEAM Employees", team.employee.length);
}
or this for number of employees in all teams:
const numberOfAllEmployees = teams.map(team => team.employee.length).reduce((a,b) => a + b);
Upvotes: 2