如何使用javascript在具有不同键值对的JSON数组上循环,以根据html中的条件显示特定值



假设我的JSON数组如下所示:

[{
"type": "Sweatshirt",
"brand": "H&M",
"Color": "Yellow",
"Neck": "Turtle neck",
"Arm": "Full Arm"
},
{
"type": "Sweatshirt",
"brand": "PUMA",
"Color": "Black",
"Neck": "Round neck",
"Arm": "Full Arm"
},
{
"type": "Dresses",
"Length": "knee length",
"Occasion": "Party",
"Neck": "Halter neck"
},
{
"type": "Dresses",
"Length": "Floor length",
"Occasion": "Casual",
"Neck": "Boat neck"
}
]

我如何在数组上循环,检查type是连衣裙还是毛衣,并在HTMLdiv中显示各自的值

以下是一个示例,它将向您展示如何循环并将值分配给html元素

此示例仅用于演示

array=[{ "type": "Sweatshirt", "brand": "H&M", "Color": "Yellow", "Neck": "Turtle neck", "Arm": "Full Arm" }, { "type": "Sweatshirt", "brand": "PUMA", "Color": "Black", "Neck": "Round neck", "Arm": "Full Arm" }, { "type": "Dresses", "Length": "knee length", "Occasion": "Party", "Neck": "Halter neck" }, { "type": "Dresses", "Length": "Floor length", "Occasion": "Casual", "Neck": "Boat neck" }]
disp=document.getElementById("disp")

array.forEach(o=>{
if(o.type=="Sweatshirt"){
type=document.createElement("li")
brand=document.createElement("li")
type.textContent=o.type
brand.textContent=o.brand
disp.appendChild(type)
disp.appendChild(brand)
}})
<div id="disp7"><ul id="disp"></ul></div>

最新更新