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.
const json_object =
{
"item1":{
"name": "apple",
"value": 2,
},
"item2":{
"name": "pear",
"value": 4,
}
}
for(let item in json_object){
console.log("ITEM = " + item);
for(let property in json_object[item]){
console.log(?); // Here is the issue
}
}
You are accessing an object's value using its key in json_object[item]
so just keep drilling down into the object.
for(let item in json_object){
console.log("ITEM = " + item);
for(let property in json_object[item]){
console.log(json_object[item][property]);
}
}
const json_object = { "item1":{ "name": "apple", "value": 2, }, "item2":{ "name": "pear", "value": 4, } }; for(let item in json_object){ console.log("ITEM = " + item); for(let property in json_object[item]){ console.log(`key:${property}, value:${json_object[item][property]}`); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.