3

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.

2 Answers 2

12

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>

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

Comments

0

Something like this

const bills = salary.map((s)=> s.bills)

_(bills).map((objs,key)=>({
    'milk': _.sumBy(objs, 'milk')
})).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.