How to loop through JSON in JavaScript

When dealing with data in a JSON format, there are situations where you want to loop through every possible property. Typically, this is when you have a JSON object containing various information from an endpoint.

Let’s say you have an object like so:

const json = '{"name": "Tommy", "secondName":"Vercetti", "count":"42", "age": "30"}';

We first want to parse the JSON to make it iterable as a normal Object:

const parsedJSON = JSON.parse(json);

If we want the values of each property we can do the following:

for( let prop in parsedJSON ){
    console.log( json[parsedJSON] );
}

We cycle through each property and output the value by referencing the current prop in our object.

And if we want the names of the property keys we can iterate through them like so:

Object.keys(parsedJSON).forEach(item => console.log(item))
// name
// secondName
// count
// age

We can take this even further by transforming the JSON object into array entries that represent the original key/value pairs. Since each key/value pair is now an array we can use a standard array method to iterate through the data.

Overall, while JSON itself isn’t iterable it can be parsed into a type that is.

 

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.