I’m looking for a solution to loop through a nested JSON object in pure JS. Indeed I’d like to console.log every item and each of its properties.
JavaScript
x
21
21
1
const json_object =
2
{
3
"item1":{
4
"name": "apple",
5
"value": 2,
6
},
7
8
"item2":{
9
"name": "pear",
10
"value": 4,
11
}
12
}
13
14
for(let item in json_object){
15
console.log("ITEM = " + item);
16
17
for(let property in json_object[item]){
18
console.log(?); // Here is the issue
19
}
20
}
21
Advertisement
Answer
You are accessing an object’s value using its key in json_object[item]
so just keep drilling down into the object.
JavaScript
1
8
1
for(let item in json_object){
2
console.log("ITEM = " + item);
3
4
for(let property in json_object[item]){
5
console.log(json_object[item][property]);
6
}
7
}
8