How to iterate through an array of objects using JavaScript

Christian Hur
1 min readNov 3, 2018

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:

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response