javascript - 访问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 ......
有人可以帮我找到如何访问这些元素吗
解决方案
这是你要找的吗?
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)
}
推荐阅读
- laravel - 雄辩的 where lower() LIKE 与 PostgrSQL Laravel
- r - R中的滚动总和
- webrtc - Asterisk MessageSend 使用 PJSIP 发送到多个设备
- typescript - 在订阅之外使用响应结果导致Angular6中的未定义
- html - 通过 Linux 应用程序显示的 HTML 页面中的 CSS 字体系列被忽略
- pdf - 获取 mutool 以输出“结构化文本(作为 xml)”
- django - Django迁移添加一个默认的UUIDField
- php - PHP如何计算数组中的“subINT”
- android - 访问整个 Xamarin 应用程序的文件夹
- c - 摆脱 IAR 编译警告 Pa039 ?“使用未对齐结构成员的地址”