Skip to content
Advertisement

Loop through a nested JSON object

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
    }
}

Advertisement

Answer

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]);
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement