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
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
now has one item in it.remove the assignment
order = order.items.push({"product": id, "quantity": q})
Just do
order.items.push({"product": id, "quantity": q})