gpt4 book ai didi

javascript - 显示嵌套的 JSON 数据

转载 作者:行者123 更新时间:2023-11-30 08:23:56 24 4
gpt4 key购买 nike

目前正在使用 Javascript 进行测验,其中问题和答案位于嵌套的 JSON 数据结构中。我的结构看起来像这样:

var quizContent = [
{
"question": "Why is the sky blue?",
"answers": [
{ "answer": "Blue light is scattered in all directions by the tiny molecules of air in Earth's atmosphere." },
{ "answer": "Idk dude" },
{ "answer": "google.com" },
{ "answer": "It just is." }
]
},
{
"question": "Why did the chicken cross the road?",
"answers": [
{ "answer": "To get to the other side." },
{ "answer": "Obama amiriteeee" },
{ "answer": "To escape genocide. "},
{ "answer": "To find itself." }
]
}
]

显然这是一种有点滑稽的方法,但我有点坚持获取问题的值以及可用答案的逻辑。

现在我将只通过日志 console.log 语句显示进度。

for (var i = 0; i < quizContent.length; i++){
var obj = quizContent[i];
for (var key in obj) {
console.log(obj[key]);
}
}

这似乎得到了我需要的东西,但最终我需要更进一步,分别将问题放在标题标签中,并将答案放在列表项中,因此拥有这种控制权很重要。

任何输入将不胜感激。提前谢谢你。

最佳答案

如果你想在页面上展示你的问题和答案,这种代码将创建一些东西,通过你的对象并允许参与者选择一个响应:

var quizContent = [
{
"question": "Why is the sky blue?",

// note lack of "answer" key for each answer.
"answers": [
"Blue light is scattered in all directions by the tiny molecules of air in Earth's atmosphere.",
"Idk dude",
"google.com",
"It just is."
]
},
{
"question": "Why did the chicken cross the road?",
"answers": [
"To get to the other side.",
"Obama amiriteeee",
"To escape genocide. ",
"To find itself."
]
}
];

form_div_html = '';
quizContent.forEach(function(row,index){
form_div_html += "<h1>"+row.question+"</h1>";
row.answers.forEach(function(answer){
form_div_html += "<label><input type='radio' name='question_"+index+"' value='"+answer+"'>"+answer+"</label><br>";
});
form_div_html += "<br>";
});
document.getElementById("form_div").innerHTML = form_div_html;
<div id="form_div"></div>

我已经编辑了您的对象的结构,使其更易于循环。另请注意,使用标签可以让用户灵活地点击单选按钮或标签中的任何文本。

关于javascript - 显示嵌套的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com