Reputation: 3
I have an array of object in this format:
data= [ { 'a': [{"_id":"aa","type":"credit","amount":500}]},
{ 'b': [{"_id":"ba","type":"credit","amount":600},
{"_id":"bb","type":"refund","amount":200}]},
{ 'a': [{"_id":"aaa","type":"credit","amount":600},
{"_id":"aab","type":"credit","amount":200}]}]
All i want to do is to achieve an object like this:
result=[ { 'a': 500 },{ 'b': 600},{ 'a': 800} ]
This basically adds up the amount field from the objects which does not have a type refund.
I have tried something with _.reject and _.sumBy of lodash but failed to get the desired output.
Upvotes: 0
Views: 759
Reputation: 7406
Something like:
const data = [{'a':[{"_id":"aa","type":"credit","amount":500}]},{'b':[{"_id":"ba","type":"credit","amount":600},{"_id":"bb","type":"refund","amount":200}]}]
const sum = (items) => _.chain(items)
.reject({ type: 'refund' })
.sumBy('amount')
.value();
const res = _.map(data, item => _.mapValues(item, sum));
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Upvotes: 2
Reputation: 7291
Are you opposed to using standard javascript?
In this example, I use map
to iterate through each part of the array and reduce
to sum the amounts.
const objs = [{'a':[{"_id":"aa","type":"credit","amount":500}]},{'b':[{"_id":"ba","type":"credit","amount":600},{"_id":"bb","type":"refund","amount":200}]}]
let newObjs = objs.map((o) => {
let key = Object.keys(o)[0];
let amount = o[key].length > 1 ? o[key].reduce((a, b) => {
return {
amount: a.amount + (b.type == "refund" ? 0 : b.amount)
}
}).amount :
o[key][0].type == "refund" ? 0 : o[key][0].amount;
return JSON.parse(`{"${key}":${amount}}`)
})
console.log(newObjs)
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Upvotes: 1