Top 3 Ways to Loop Through a JSON Object in JavaScript
2 min readSep 27, 2022
1. Use a for...in
Loop
A for…in loop iterates over all enumerable properties of an object:
const res = JSON.parse(xhr.responseText);
for (const key in res){
if(obj.hasOwnProperty(key)){
console.log(`${key} : ${res[key]}`)
}
}
// id : H6Elb2LBdxc
// joke : What's blue and not very heavy? Light blue.
// status : 200
2. Use Object.entries
, Object.values
or Object.entries
An alternative approach to above is to use one of Object.keys(), Object.values() or Object.entries(). These will return an array which we can then iterate over.
Let’s take a look at using Object.entries
. This returns an array of the key/value pairs of the object we pass it:
const res = JSON.parse(xhr.responseText);Object.entries(res).forEach((entry) => {
const [key, value] = entry;
console.log(`${key}: ${value}`);
});// id: SvzIBAQS0Dd
// joke: What did the pirate say on his 80th birthday? Aye Matey!
// status: 200
3. Using the Fetch API
While the method above using the XMLHttpRequest
object works just fine, it can get unwieldy pretty quickly. We can do better.
The Fetch API is a Promise-based API, which enables a cleaner, more concise syntax and helps keep you out of callback hell. It provides a fetch()
method defined…