Suppose I have an array of Object as:
Expected O/P : {alpha:4, beta:8}
For this I tried as:
const apple = [{
name: 'alpha',
details: [{
"attachment": [123, 456]
}, {
"attachment": [1454, 1992]
}]
},
{
name: 'beta',
details: [{
"attachment": ["12", 189]
}, {
"attachment": ["maggi", 1890, 2000]
}, {
"attachment": [1990, 2001, 2901]
}]
}
];
const appleDetails = [];
for (let i = 0; i < apple.length; i++) {
for (let j = 0; j < apple[i].details.length; j++) {
const {
name
} = apple[i];
const {
attachment
} = apple[i].details[j]
appleDetails.push({
name,
attachment
})
}
}
let appleData = [];
appleDetails.forEach(({
name,
attachment
}) => {
attachment.forEach((attatchId) => {
appleData.push({
name,
_id: attatchId
})
})
})
const eachAppleCount = appleData.reduce((acc, item) => {
const key = item.name
if (!acc.hasOwnProperty(key)) {
acc[key] = 0
}
acc[key] += 1
return acc
}, {})
console.log(eachAppleCount);
This gives the O/P as required i.e. : {alpha:4, beta:8}
But the process involved is too much, is there any more efficient way such that,by using:
const apple = [{
name: 'alpha',
details: [{
"attachment": [123, 456]
}, {
"attachment": [1454, 1992]
}]
}, {
name: 'beta',
details: [{
"attachment": ["12", 189]
}, {
"attachment": ["maggi", 1890, 2000]
}, {
"attachment": [1990, 2001, 2901]
}]
}];
We can count the value for each apple name. If anyone needs any further information please do let me know.