Search code examples
lodash

how to sum from array of object using lodash only?


hey I want to calculate the sum of one property from array of object using lodash

suppose the array of object looks like this ...

salary":[{
   "bills":[{"electricity":300,"milk":500},
            {"electricity":240,"milk":200},
            {"electricity":800,"milk":900}]    
}]

I want to calculate the sum of 'milk' from that object using lodash.


Solution

  • Use nested _.sumBy() calls. The internal gets the sum of milk from one salary, and the external sums all salaries:

    const data = {"salary":[{"bills":[{"electricity":300,"milk":500},{"electricity":240,"milk":200},{"electricity":800,"milk":900}]}]}
    
    const result = _.sumBy(data.salary, ({ bills }) => _.sumBy(bills, 'milk'))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>