0

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.

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Beautiful, clean answer
It is not okay to add another question after your original question was solved, if this answer solved your question, please mark it as the correct solution.
1

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.


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.