Reputation: 105
I am retrieving data via JSON but the problem is that I am getting error as such "Cannot read property 'productid' of undefined".
JSON File (data.json)
{
"Products": [
{
"productid": "135",
"productname": "Shirt",
"productqty": "3",
"seller_3": "150.00",
"seller_2": "151.00",
"seller_7": "153.00",
"seller_6": "159.00",
"seller_5": "155.00",
"seller_1": "157.00",
"seller_4": "152.00"
}
]
}
The execution code is
var itemQty = 134;
$.getJSON( "../data.json", function(data) {
if (data.Products.length == 0) {
/*do nothing*/
} else if(data.Products.length > 0){
for (var i = 0; i < data.Products.length; i++) {
console.log(data.Products[i].productid); // ITS RETURN THE VALUE 135
if (data.Products[i].productid == itemID) { // <--- ERROR THIS LINE
if (data.Products[i].productqty == itemQty) {
newQuantity = eval(data.Products[i].productqty);
} else {
var newQuantity = eval(itemQty);
}
if (newQuantity > options.quantityLimit) {
newQuantity = options.quantityLimit
}
data.Products[i].productqty = newQuantity;
} else {
data.Products.push(cartItem);
}
}
}
}
In the console.log, it returns the value which is 135, where as when comparing in the IF statement, I am getting the error Cannot read property 'productid' of undefined.
Upvotes: 1
Views: 3359
Reputation: 688
It looks like you are modifying the list of Products from inside the loop. So take a closer look at whatever is setting the value for cartItem
.
for (var i = 0; i < data.Products.length; i++) {
...
data.Products.push(cartItem);
}
It is a bad idea to add new items to a list while you're iterating over it. You are likely to have an infinite loop depending on how itemID
and cartItem
are set.
Try reading the .length
value one time before starting the loop, so new items won't be iterated:
for (var i = 0, len = data.Products.length; i < len; i++) {
...
}
Upvotes: 2