Reputation: 441
I'm trying to implement basic shopping cart, but I'm stuck at one problem. I'm need to check if item already exist in cart and if it exist increment its quantity. But when I'm trying to compare purchases[i].id = this.arr[i].id;
it gives me following error
TypeError: Cannot set property 'id' of undefined`
Exapmle of cart code realization:
var Cart = {
AddToCart:function(arr,buttonId){
var purchases = [{id: null,name: null,price: null,quantity: 0}];
this.arr = arr;
this.buttonId = buttonId;
for(var i = 0; i <this.arr.length; i++){
if(this.buttonId === this.arr[i].id && purchases[i].id === this.arr[i].id && $("#oredersUL, #" + this.buttonId).length){
purchases[i].quantity++;
console.log(purchases[i]);
}
else {
purchases[i].id = this.arr[i].id;
purchases[i].name = this.arr[i].name;
purchases[i].price = this.arr[i].price;
purchases[i].quantity++;
console.log(purchases);
}
}
}
};
Example of using:
$("#list").delegate("button",'click',function(){
var buttonId = $(this).attr('id');
Cart.AddToCart(phones,buttonId);
});
Given array:
var phones = [
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb).",
"price": 150
},
Upvotes: 1
Views: 427
Reputation: 58405
You are asking whether purchases[i].id === this.arr[i].id
but purchases[i]
doesn't exist yet (even though other values for i
may).
First check if the element at index i
exists:
if (typeof purchases[i] === 'undefined')
Now, if purchases[i]
doesn't exist you need to create it. I would do that using push
:
purchases.push({
"id": this.arr[i].id,
"name": this.arr[i].name,
"price": this.arr[i].price,
// I have not included "quantity" here because
// what you have right now doesn't make sense:
// purchases[i] doesn't exist
// so the same is true for purchases[i].quantity
});
Using .push
will mean that you can't trust your array index for the content of each array element (but that's probably a bad idea anyway - that's why your objects have an id
).
This means that to update the correct array element you will want to do something like this (finding an object in an array by its id)
Upvotes: 1