Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a JSON Array gives "undefined" results [duplicate]

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.

like image 625
Momo Avatar asked Oct 30 '15 23:10

Momo


1 Answers

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);
}
like image 153
kemicofa ghost Avatar answered Oct 20 '22 23:10

kemicofa ghost