How to Iterate Through an Array of Objects Using JavaScript
November 3, 2018
Suppose you have an array of objects.
JavaScript
x
4
1
var zipCodes = [
2
{"ZIP": 30001, "LAT": 30.750633, "LNG": -63.997177},
3
{"ZIP": 10001, "LAT": 40.750633, "LNG": -73.997177 },
4
{"ZIP": 20001, "LAT": 50.750633, "LNG": -83.997177 }];
If you want to grab only the LAT and LNG values for a matching ZIP (as the key), you can easily use the for loop:
JavaScript
xxxxxxxxxx
1
9
1
var key = 10001; //the zip code you want to search
2
var lng, lat;
3
for(var i=0; i < zipCodes.length; i++){
4
if(zipCodes[i].ZIP == key){
5
lat = zipCodes[i].LAT;
6
lng = zipCodes[i].LNG;
7
break;
8
}
9
}
However, if you just want to loop through the entire array and print them out, you could use the object.forEach() method:
JavaScript
xxxxxxxxxx
1
4
1
zipCodes.forEach(function(item,index){
2
lat = item.LAT;
3
lng = item.LNG;
4
});
You can try running the code here: