index.html

Javascript Loop Array Parsed from JSON

Word count: 65Reading time: 1 min
2019/09/25 Share

Suppose we need to loop the objects in users array in the following json.

1
2
3
4
5
6
7
8
9
10
{
"users": [
{
"userID": "foo"
},
{
"userID": "bar"
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
let data = JSON.parse(jsonString);

console.log(data);

// This throws error "ReferenceError: user is not defined"
for (user of data.users) {
console.log(user.userID);
}

// Working solution
data.users.forEach((obj) => {
console.log(obj.userID);
});
CATALOG