Javascript : Not Understanding Looping on Associative Array

68 Views Asked by At

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>
3

There are 3 best solutions below

3
On BEST ANSWER

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);
}

0
On

The for...in loops iterates over keys , so in an array itll be

 0,1,2

and these numbers dont have an iName. You may want to iterate over values with the for..of loop:

for(var img of gallery.imgs)
0
On

you should use a for...of / forEach / for loop instead of the for..in loop you used.

to quickly demonstrate the difference between the for..in and the for..of loop:

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

that means that it will not really go through array's elements you wanted but over all enumerable properties of the object. (in javascript all the variables are objects)

I'd suggest you go with something like:

gallery.imgs.forEach(img => {
  console.log(img.iName) // "File1.jpg" , "File2.jpg", ...
});