循环遍历嵌套的 JSON 对象

时间:2021-03-04 17:19:21

标签: javascript html json

我正在寻找一种在纯 J​​S 中遍历嵌套 JSON 对象的解决方案。 事实上,我想对每个项目及其每个属性进行 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
    }
}

2 个答案:

答案 0 :(得分:0)

您正在使用 json_object[item] 中的键访问对象的值,因此只需继续深入查看该对象。

for(let item in json_object){
    console.log("ITEM = " + item);

    for(let property in json_object[item]){
        console.log(json_object[item][property]);
    }
}

答案 1 :(得分:0)

    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]}`);
       }
    }