Home > Enterprise >  Node Ecommerce Cart NaN Issue
Node Ecommerce Cart NaN Issue

Time:10-22

Working on calculating a total for my cart which it seems that I'm running into a number issue. I'm not really sure where I am going wrong with this function. Please disregard if I haven't calculated the totals correctly as I just coded it, but with the JSON I am passing numbers and not strings.

JSON

{
    "id": "611afa8b9069c9126cff3357",
    "discount": {
        "title": "None",
        "type": "None",
        "percent": 0
    },
    "items": [
        {
            "sku": 1000,
            "qty": 2,
            "price": 10.99
        },
        {
            "sku": 1001,
            "qty": 2,
            "price": 16.99
        },
        {
            "sku": 1003,
            "qty": 1,
            "price": 15.99
        }
    ]
}
const calculateTotal = (items, discount) => {
  let total = 0;
  let discountAmt = 0;

  console.log(discount);
  console.log(items);
  console.log(items.length);

  for (let i = 0; (j = items.length), i < j; i  ) {
    discountAmt = 0;

    if (discount.type == "Item" && discount.itemNum == j.sku) {
      discountAmt = j.price * (discount.percent / 100);
      total = total - discountAmt;
    } else {
      total = total   j.price * j.qty;
    }
  }

  if (discount.type == "Order") {
    discountAmt = 0;
    discountAmt = total * (discount.percent / 100);
    total = total - discountAmt;
  }

  console.log(total);

  return total;
};

Console Returning

{ title: 'None', type: 'None', percent: 0 }
[
  { sku: 1000, qty: 2, price: 10.99 },
  { sku: 1001, qty: 2, price: 16.99 },
  { sku: 1003, qty: 1, price: 15.99 }
]
3
NaN
NaN

CodePudding user response:

If you want to loop through your items, then your loop is not correct.

You can do something like this:

for (let i = 0; i < items.length; i  ) { // i as index
    let j = items[i]; // j will have the object based on the index
    discountAmt = 0;

    if (discount.type == "Item" && discount.itemNum == j.sku) {
      discountAmt = j.price * (discount.percent / 100);
      total = total - discountAmt;
    } else {
      total = total   j.price * j.qty;
    }
}

or much simpler:

for (let j of items) { 
    discountAmt = 0;

    if (discount.type == "Item" && discount.itemNum == j.sku) {
      discountAmt = j.price * (discount.percent / 100);
      total = total - discountAmt;
    } else {
      total = total   j.price * j.qty;
    }
}
  • Related