1

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.

2
  • 2
    Can you reproduce the problem on jsfiddle.net? Commented Dec 8, 2013 at 13:49
  • Why the eval's when you could just use parseInt's? Commented Dec 8, 2013 at 13:56

1 Answer 1

2

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++) {
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Noted. I modified the script. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.