8

I have a JSON String being parsed (in a response var) from AJAX:

The JSON

{
   "TheArray":[  
      {  
         "AlmostThere": {  
            "whatWeAreLookingFor":"Hello"
         }
      },
      {
        "AlmostThere": {
            "whatWeAreLookingFor":"Goodbye"
        }
      }
   ]
}

The JSON being parsed

var jsonData = JSON.parse(response); //response is the string version of the JSON code!

Now, I need to loop into the JSON array, hereby mentioned as TheArray. I do this:

Looping TheArray

for (var contents in jsonData["TheArray"]) {

}

And inside there, we get the value of the whatWeAreLookingFor element:

for (var contents in jsonData["TheArray"]) {
    console.log(contents.whatWeAreLookingFor + "!");
}

But there is a catch! The console outputs... undefined!. - I have tried multiple ways to make this work, such as using contents["whatWeAreLookingFor"] and what-not, but I still get the same results.

Momo
  • 3,542
  • 4
  • 21
  • 34
  • 2
    [Don't use `for... in` for looping over Arrays](http://stackoverflow.com/questions/242841/javascript-for-in-vs-for) - use a regular `for` loop, `forEach`, or `for... of` if you can use ES6. – joews Oct 30 '15 at 23:22
  • Hint: log `contents` inside your loop. It won't be what you expect. – joews Oct 30 '15 at 23:25
  • `for (var contents in jsonData.TheArray) { console.log(jsonData.TheArray[contents].AlmostThere.whatWeAreLookingFor + "!"); }` – Ryu Oct 30 '15 at 23:29

3 Answers3

5

You forgot to access AlmostThere

  jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor

for (var i = 0; i < jsonData.TheArray.length; i++) {
    console.log(jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor);
}
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

If you loop your array TheArray in your way, the contents var will become these two objects:

{  
     "AlmostThere": {  
        "whatWeAreLookingFor":"Hello"
     }
}

and

{
    "AlmostThere": {
        "whatWeAreLookingFor":"Goodbye"
    }
}

Now you want to access the value with

contents.whatWeAreLookingFor

but this attribute is undefined for these objects. So your console logs undefined. You have to access the value with that:

contents.AlmostThere.whatWeAreLookingFor

So you get the object AlmostThere and select the attribute whatWeAreLookingFor.

If your using jquery you should use:

$.each(jsonData.TheArray, function() {
     console.log(contents.AlmostThere.whatWeAreLookingFor + '!');
});

API: http://api.jquery.com/jquery.each/

Sim
  • 3,279
  • 1
  • 17
  • 23
0

for... in iterates over the keys of an object. For an array, that means (approximately) the indexes 0, 1, 2, etc.

You could use Array.prototype.forEach instead:

jsonData.theArray.forEach(function(contents) {
  console.log(contents.AlmostThere.whatWerAreLookingFor);
})
Community
  • 1
  • 1
joews
  • 29,767
  • 10
  • 79
  • 91