Calculating sum in object

Is there another way to find the total sum in an object, What if we had a bunch of properties ? How would you approach this…?

cartForParty = {coldrinks:10,beers:10,chips:5,ballons:10,cakes:10};

function calcTotalPrice(cartForParty){
    var sum = cartForParty.coldrinks + cartForParty.beers + cartForParty.chips + cartForParty.ballons + cartForParty.cakes;
    return `Your total cart is $${sum}`;

you can use for ... in loop.

1 Like

Hi there oussama, Thank you for the suggestion, i will definitely try that out with for … in loop. Much Thanks!

In ultra modern javascript you could use Object.values (only available using the Babel transpiler or Typescript I think).

const sumObj = (o) => Object.values(o).reduce((sum, n) => sum + n, 0)

But rn the best approach is the for-in loop which gives you a list of “keys” (props) so that you can extract the values using bracket notation.