skip to Main Content

in the following function, q and id log 1 and 2 respectively but the order equals 1 instead of {items: [{"product": 2, "quantity": 1}]}.

function addToCart(id) {
        q = $('.shopify-buy__quantity').val();
        console.log("q: " + q)
        console.log("id: " + id)
        var order = {items: []}
        order = order.items.push({"product": id, "quantity": q})
        console.log('order: ' + order)
        order = JSON.stringify(order)
        storage.setItem('domehaOrder', order)
        updateCart()
}

How can I fix this?

2

Answers


  1. Array.push() doesn’t return the object that owns the array. It alters the array object itself by adding the new item to the end, and then it returns the new length of the array.

    Just call it, don’t assign the length of the array to order.

    order.items.push({"product": id, "quantity": q})
    

    order.items now has one item in it.

    Login or Signup to reply.
  2. remove the assignment order = order.items.push({"product": id, "quantity": q})

    Just do order.items.push({"product": id, "quantity": q})

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search