Javascript: add value while looping using forEach()

59 Views Asked by At
cart = [
  {
    "name": "item1",
    "sellingprice": 30,
    "barcode": 1494857
  },
  {
    "name": "item2",
    "sellingprice": 60,
    "barcode": 1235858
  },
  {
    "name": "item3",
    "sellingprice": 100,
    "barcode": 1568858
  }
]

    function totalbill(){
    Object.keys(cart).forEach(key => {
    total += cart[key].sellingprice;
    });

console.log(total);

output: 3060100

it works doing it manually

console.log(cart[0].sellingprice+cart[1].sellingprice+cart[2].sellingprice);

output: 190

Also tried using parseInt() didnt word

2

There are 2 best solutions below

0
Pipo Bizelli On

First of all, have you tried declared the total var before the method totalbill?

And then you can try:

var total = 0;
function totalbill(){
    Object.keys(cart).forEach(key => {
    total = total + parseInt(cart[key].sellingprice);
    });
0
AudioBubble On

You have a misunderstanding on your data structure.

What you want is something like below.

const cart = [ { "name": "item1", "sellingprice": 30, "barcode": 1494857 }, { "name": "item2", "sellingprice": 60, "barcode": 1235858 }, { "name": "item3", "sellingprice": 100, "barcode": 1568858 } ];

let total = 0;

function totalbill() {

  cart.forEach(c => {
    total += c.sellingprice;
  });
}

totalbill();
console.log('total', total);