Consider the following JSON string:
[{"ElementID1":{"latitude":"10.02483","longitude":"70.753464"}},{"ElementID2":{"latitude":"10.029301","longitude":"70.751892"}},{"ElementID3":{"latitude":"10.029568","longitude":"70.751856"}}]
Which is contained in the "data" variable:
var response = JSON.parse(data);
How do I go through this result? It is clear for me that I can access this first as an array:
for(var element in response)
{
}
But I don't know what "ElementID1" will be. It can be any string so i cant just do something like
element.elementID.latitude
To retrieve the object latitude. And i would also like to be able to get that picture id itself.
I think this is a simple question but i have tried googling for the answer for a while without any progress.
for..in
to iterate over an array, use the vanillafor
. I'm not sure I understand completely what you are asking, but the answer probably is, well,for..in
. Use this loop in any object and it will loop over its keys just as it is looping over the array's keys. In other words: is this what you want?:for(var i=0, n=response.length; i<n; i++) { for(var key in response[i]) { console.log(key); } }
for...in
loops in JS don't actually give you the element, just the index. Demo