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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With