Looping through a JSON Array gives "undefined" results

时间:2015-10-30 23:19:39

标签: javascript jquery arrays json

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.

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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/

答案 2 :(得分: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); })