I cannot find solution to this problem.
I have array:
const taxItems = [{
taxCode: '430',
taxAmount: 2,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '430',
taxAmount: 4,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '431',
taxAmount: 5,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '430',
taxAmount: 6,
ItemTaxPercentage: 20,
taxCategory: '2'
}
]
And from this array I want to sum up all objects by taxCode.I want to have results like this:
var results = [{
taxCode: '430',
taxAmount: 12,
ItemTaxPercentage: 20,
taxCategory: '2'
},
{
taxCode: '431',
taxAmount: 5,
ItemTaxPercentage: 20,
taxCategory: '2'
}
]
I tried to use lodash:
var results =
lodash(taxItems)
.groupBy('taxCode')
.map((objs, key) => ({
'taxCode': key,
'taxAmount': lodash.sumBy(objs, 'taxAmount') }))
.value();
But it only works with key value pair. I will loose the original structure of the object.
What would be the correct solution to my problem?