How To Get Max Of In Array Of Objects
I am trying to summarize a JSON var data = [ { customerName: 'Customer1', customerId: '1234', invoices: [ { id: '647549', transactionId: 'INV01'
Solution 1:
It's a fairly straightforward map()
of the data array, with a nested reduce()
call to refactor the invoices array. The first element in the invoices
array is passed as the initial accumulator and it is only refactored if there are multiple in the array. Since we are returning a new object on each map iteration we can simply omit the creditMemo
property.
I agree with the commenter regarding storing multiple id
properties in arrays rather than concatenated strings – both for later use and simplicity of refactoring.
const summary = data.map(({ customerName, customerId, invoices }) => {
const debitSummary = invoices.reduce((acc, inv, i) => {
if (i) {
acc = {
...acc,
id: acc.id + '-' + inv.id,
transactionId: acc.transactionId + '-' + inv.transactionId,
debit: acc.debit + inv.debit,
date: newDate(inv.date) > newDate(acc.date) ? inv.date : acc.date,
}
}
return acc;
}, invoices[0]);
return { customerName, customerId, invoices: [{...debitSummary}] };
});
console.log(summary);
.as-console-wrapper { max-height: 100%!important; top: 0; }
<script>const data = [{ customerName: "Customer1", customerId: "1234", invoices: [{ id: "647549", transactionId: "INV01", date: "10/12/2020", debit: 371.93, dueDate: "09/02/2021" }], creditmemo: [] }, { customerName: "Customer5", customerId: "5678", invoices: [{ id: "631109", transactionId: "INV05", date: "09/12/2020", debit: 206.92, dueDate: "08/02/2021" }, { id: "664359", transactionId: "INV06", date: "11/12/2020", debit: 91.91, dueDate: "10/02/2021" }], creditmemo: [] }];
</script>
Post a Comment for "How To Get Max Of In Array Of Objects"