Search code examples
javascriptjsonfor-in-loop

Javascript : Not Understanding Looping on Associative Array


I have a JSON object (well that is what I thought I had defined) and I am trying to access the values of an array within it. It is looping three times which is correct but the value of img.iName is always undefined

What have I misunderstood ?

<div id="dbgDIV">Debug Div<br></div>
<script>
    // imgs as a JSON array
    var gallery = {"imgs":
                [ // Height and Width to be added
                    {"iName":"File1.jpg", "tName": "File1_th.jpg","cap":"This is a Caption for File1"},
                    {"iName":"File2.jpg", "tName": "File2_th.jpg","cap":"This is a Caption for File2"},
                    {"iName":"File3.jpg", "tName": "File3_th.jpg","cap":"This is a Caption for File3"}
                ],
                "imgCount":"3"
    };
    var dbgDIV = document.getElementById("dbgDIV");
    for (var img in gallery.imgs) {
        dbgDIV.innerHTML = dbgDIV.innerHTML + "img=" + img.iName + "<br>";
        console.log(img.iName);
    }

</script>

Solution

  • The for...in loop is the trouble. Just use a traditional for loop to index into the array:

    var gallery = {
      "imgs": [
        {
          "iName": "File1.jpg",
          "tName": "File1_th.jpg",
          "cap": "This is a Caption for File1"
        },
        {
          "iName": "File2.jpg",
          "tName": "File2_th.jpg",
          "cap": "This is a Caption for File2"
        },
        {
          "iName": "File3.jpg",
          "tName": "File3_th.jpg",
          "cap": "This is a Caption for File3"
        }
      ],
      "imgCount": "3"
    };
    var dbgDIV = document.getElementById("dbgDIV");
    for (var i = 0; i < gallery.imgs.length; i++) {
      var img = gallery.imgs[i];
      console.log(img.iName);
    }