How to iterate through an array of objects using JavaScript
Suppose you have an array of objects.
const zipCodes = [
{"ZIP": 30001, "LAT": 30.750633, "LNG": -63.997177},
{"ZIP": 10001, "LAT": 40.750633, "LNG": -73.997177 },
{"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:
const key = 10001; //the zip code you want to search
let lng, lat;for(let i=0; i < zipCodes.length; i++){
if(zipCodes[i].ZIP == key){
lat = zipCodes[i].LAT;
lng = zipCodes[i].LNG;
break;
}
}
However, if you just want to loop through the entire array and print them out, you could use the object.forEach() method:
zipCodes.forEach(function(item,index){
lat = item.LAT;
lng = item.LNG;
});
You can try running the code here:
—
My online training courses:
- Full-Stack Web Development with Django and Angular 8
- Full-Stack Web Development with Flask
- The DOM in JavaScript, jQuery, AngularJS, and React (Lynda.com).
- The DOM in JavaScript, jQuery, AngularJS, and React (LinkedIn)
- Building JSF Web Applications with Java EE 7 (Lynda.com)
- Building JSF Web Applications with Java EE 7 (LinkedIn)
- Troubleshooting Vue.js (packtpub.com)
- Angular 7 New Features
My book “Developing Business Applications for the Web: With HTML, CSS, JSP, PHP, ASP.NET, and JavaScript” is available on Amazon and MC Press.
Check out my author page at http://amazon.com/author/christianhur