Below is a code that adds the amount if the CategoryId
is the same and creates a new line item
per CategoryId
.
self.OriginalLineItems = [
{ CategoryId: 'Cat1', Amount: 15, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 30, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 20, Type: 'TypeB' },
{ CategoryId: 'Cat2', Amount: 10, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 5, Type: 'TypeB' }]
self.newLineItems = [];
self.OriginalLineItems.forEach(function (o) {
if (!this[o.CategoryId]) {
this[o.CategoryId] = { CategoryId: o.CategoryId, Amount: 0, Type: o.Type };
self.newLineItems.push(this[o.CategoryId]);
}
this[o.CategoryId].Amount += o.Amount;
}, Object.create(null));
Which would result in the array below:
self.newLineItems = [{ CategoryId: 'Cat1', Amount: 65, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 15, Type: 'TypeA' }]
But I want to add a new condition which is Type, How do I get the results below?
self.newLineItems = [{ CategoryId: 'Cat1', Amount: 45, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 20, Type: 'TypeB' },
{ CategoryId: 'Cat2', Amount: 10, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 5, Type: 'TypeB' }]
I could not find a solution on the linked question.