I have an array of objects which each may have collection of transactions I need to extract two values of the array
[
{
"id": "1",
"value": 2343,
"transactions": [
{
"id": 88,
"amount": 34,
},
{
"id": 89,
"amount": 111,
}
]
},
{
"id": "2",
"value": 345,
"transactions": [
{
"id": 90,
"amount": 44,
},
{
"id": 91,
"amount": 112,
}
]
}
]
The first one I achieve by
objects.reduce((acc, transaction) => acc + transaction.value, 0);
But the second one is too difficult for me to achieve; do I loop and reduce each object?
With lodash you can use _.sumBy()
to get the value, and nesting _.sumBy()
calls to get the transactions amount:
const data = [{"id":"1","value":2343,"transactions":[{"id":88,"amount":34},{"id":89,"amount":111}]},{"id":"2","value":345,"transactions":[{"id":90,"amount":44},{"id":91,"amount":112}]}];
const value = _.sumBy(data, 'value');
const transactions = _.sumBy(data, ({ transactions }) => _.sumBy(transactions, 'amount'));
console.log('value: ', value);
console.log('transactions: ', transactions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Without lodash, you can use the same logic with Array#reduce:
const data = [{"id":"1","value":2343,"transactions":[{"id":88,"amount":34},{"id":89,"amount":111}]},{"id":"2","value":345,"transactions":[{"id":90,"amount":44},{"id":91,"amount":112}]}];
const value = data.reduce((acc, { value }) => acc + value, 0);
const transactions = data.reduce((acc, { transactions }) =>
transactions.reduce((acc, { amount }) => acc + amount, 0)
, 0);
console.log('value: ', value);
console.log('transactions: ', transactions);
This may be old fashioned, but I like .forEach()
loops for a simple problem like this. They are straightforward and easy to understand.
let objects = [
{
"id": "1",
"value": 2343,
"transactions": [
{ "id": 88, "amount": 34, },
{ "id": 89, "amount": 111, }
]
},
{
"id": "2",
"value": 345,
"transactions": [
{ "id": 90, "amount": 44, },
{ "id": 91, "amount": 112, }
]
}
];
let totalValue = 0;
let totalTransactionAmount = 0;
objects.forEach( function( object ) {
totalValue += object.value;
object.transactions.forEach( function( transaction ) {
totalTransactionAmount += transaction.amount;
});
});
console.log( totalValue, totalTransactionAmount );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With