I have a nested array that I want to group according to branch, department, and product. For each of these products, I want to get the sum of the quantity.
This is my array:
const array = [{
"branch": "Main Office",
"department": "Accounting",
"transaction": [{
"referenceCode": "REF1",
"product": [{
"product": "pen",
"quantity": 5, "color": "blue", "size": 10
},
{
"product": "marker",
"quantity": 7, "color": "black", "size": 15
},
{
"product": "paper",
"quantity": 27, "color": "gree", "size": 14
},
]
},
{
"referenceCode": "REF2",
"product": [{
"product": "pen",
"quantity": 3, "color": "brown", "size": 9
},
{
"product": "marker",
"quantity": 6, "color": "pink", "size": 6
},
{
"product": "paper",
"quantity": 22, "color": "indigo", "size": 5
},
]
},
],
},
{
"branch": "Sub-office",
"department": "Warehouse",
"transaction": [{
"referenceCode": "REF3",
"product": [{
"product": "pen",
"quantity": 30, "color": "blue", "size": 5
},
{
"product": "marker",
"quantity": 30, "color": "gold", "size": 34
},
]
},
{
"referenceCode": "REF4",
"product": [{
"product": "pen",
"quantity": 3, "color": "silver", "size": 2
},
{
"product": "marker",
"quantity": 6, , "color": "white", "size": 3
},
{
"product": "paper",
"quantity": 30, , "color": "violet", "size": 5
},
]
},
],
},
]
This is my desired result:
[
{ "branch": "Main Office", "department": "Accounting", "product": "pen", "quantity": 8 },
{ "branch": "Main Office", "department": "Accounting", "product": "marker", "quantity": 13 },
{ "branch": "Main Office", "department": "Accounting", "product": "paper", "quantity": 49 },
{ "branch": "Sub-office", "department": "Warehouse", "product": "pen", "quantity": 33 },
{ "branch": "Sub-office", "department": "Warehouse", "product": "marker", "quantity": 36 },
{ "branch": "Sub-office", "department": "Warehouse", "product": "paper", "quantity": 30 }
]
I believe the aggregation framework best solves this but I don't know. If there are solutions other than the aggregation framework, please let me know.