I am trying to show total count of participants based on two conditions: have "Pocu": "Da" and "Nume": "Contabilitate" from below nested array.
let popular = JSON.parse(`[
{
"id": "15f806ec-79cf-498f-8a4d-8bc8fdf8c43e",
"Nume": "negrea",
"Prenume": "ioana",
"Pocu": "Da",
"createdAt": "2022-04-27T13:17:05.000Z",
"updatedAt": "2022-04-27T13:17:05.000Z",
"deletedAt": null,
"INDICATORI": [
{
"id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
"Nume": "4S110",
"importHash": null
}
],
"Cursuri": [{
"id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
"Nume": "Contabilitate",
"importHash": null
}]
}]`);
const count = popular.reduce((total, participant) => total Math.min (participant.Cursuri
.filter(indicator => indicator.Nume === "Contabilitate").length, popular
.filter(indicator => indicator.Pocu === "Da").length), 0)
console.log(count);
output is : 85 it shoud be 20
any help is appreciated, thank you
CodePudding user response:
Here, you can use filter to put those items into the array that met these two conditions and then count the items in the array.
const count = popular.filter(item => item.Pocu === "Da" && item.Nume === "Contabilitate").length
CodePudding user response:
Please try that
const count = popular.filter(item => item.Pocu === "Da" && item.Cursuri.filter(c => c.Nume === "Contabilitate").length > 0).length;
console.log(count);
outputs 1
When searching in the nested Cursuri array we do it like below
if (item.Cursuri.filter(c => c.Nume === "Contabilitate").length > 0) {
}
or you can do it like below
if (item.Cursuri.some(c => c.Nume === "Contabilitate")) {
}
CodePudding user response:
You can simply achieve it by iterating the child objects with the help of Object.keys() along with Array.forEach() method.
Live Demo :
let popular = JSON.parse(`[
{
"id": "15f806ec-79cf-498f-8a4d-8bc8fdf8c43e",
"Nume": "negrea",
"Prenume": "ioana",
"Pocu": "Da",
"createdAt": "2022-04-27T13:17:05.000Z",
"updatedAt": "2022-04-27T13:17:05.000Z",
"deletedAt": null,
"INDICATORI": [
{
"id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
"Nume": "4S110",
"importHash": null
}
],
"Cursuri": [{
"id": "068170b3-7995-41df-8fac-4f2bc577e2c6",
"Nume": "Contabilitate",
"importHash": null
}]
}]`);
let count = 0;
popular.forEach(obj => {
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
obj[key].forEach(participant => {
if (obj.Pocu === 'Da' && participant.Nume === 'Contabilitate') {
count ;
}
})
}
});
});
console.log(count);