Search code examples
javascriptlodash

Manipulation of array of objects in javascript using lodash or underscore.js


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.


Solution

  • 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>