Обычно я создавал бы хэш-карту company id
для точек данных, но, поскольку вы специально запрашиваете массив, мы также можем использовать метод .findIndex
, чтобы проверить, существует ли компания.
const data = [{
"id":35,
"aktivis":{
"id":450,
"name":"A. Sri Nugroho Hadi",
"gender": "male",
"active_job":{
"id":491,
"id_aktivis":450,
"id_company":20,
"company":{
"id":20,
"name":"Company 1"
}
}
}
},
{
"id":36,
"aktivis":{
"id":451,
"name":"Sri ",
"gender": "female",
"active_job":{
"id":492,
"id_aktivis":451,
"id_company":21,
"company":{
"id":21,
"name":"compnay 2"
}
}
}
}
]
let companies = [];
data.forEach(employee => {
const sex = employee.aktivis.gender;
const jobData = employee.aktivis.active_job;
const companyIndex = companies.findIndex(c => c.id === jobData.company.id);
const companyData = companies[companyIndex]
if (!companyData) {
// first time encountering this company need to create a new object
companies.push({
id: jobData.company.id,
name: jobData.company.name,
employee_count: 1,
female: sex === "female" ? 1 : 0,
male: sex === "male" ? 1 : 0,
})
} else {
// company already exists in our array, just need to increment values
companies[companyIndex][sex]++
companies[companyIndex].employee_count++
}
})