简体   繁体   English

循环通过嵌套的 JSON object

[英]Loop through a nested JSON object

I'm looking for a solution to loop through a nested JSON object in pure JS.我正在寻找一种解决方案来循环遍历纯 JS 中的嵌套 JSON object。 Indeed I'd like to console.log every item and each of its properties.事实上,我想 console.log 每个项目及其每个属性。

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.您正在使用json_object[item]中的键访问对象的值,因此请继续深入了解 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]}`); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM