首页 > 解决方案 > 访问json子数据

问题描述

我试图在一个循环中附加一些标签和单选按钮到一个div中,其中文本值存储到一个json中,如:

...
},
    "Doc_3":
    {
            "Q1":{
                "desc":"description Q1",
                "radio1":"radio 1 text ",
                "radio2":"radio 2 text",
                ...
            },
            "Q2":{"desc":"description Q2"}
        }
        
}

到目前为止,我设法使用以下代码获得 Q1 和 Q2 desc:

fetch("data.json")
    .then(response => response.json())
    .then(data => {
       for(x in data.Doc_3){
          desc = data.Doc_3[x].desc
          console.log(desc)
       }
})

但我没有设法得到(在一个循环中)data.Doc_3[x].radio[y] wherey将是一个变量在循环结束时递增 1,所以我可以在我的 div 中附加 radio1、radio2、radio3 ......

有人可以帮我找到如何访问这些元素吗

标签: javascriptjson

解决方案


这是你要找的吗?

let data = {
  "Doc_3": {
    "Q1": {
      "desc": "description Q1",
      "radio1": "radio 1 text ",
      "radio2": "radio 2 text",
    },
    "Q2": {
      "desc": "description Q2"
    }
  }
}

for (x in data.Doc_3) {
  desc = data.Doc_3[x].desc
  let y = 0;
  while (++y && data.Doc_3[x]['radio' + y]) {
    console.log(y, data.Doc_3[x]['radio' + y])
  }
  console.log(desc)
}


推荐阅读