简体   繁体   English

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

[英]how to loop over JSON array having different key value pairs to display specific values depending on condition in html using javascript

Suppose my JSON array is as shown:假设我的 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"
  }
]

how can I loop over array and check if the type is dress or SweatShirt and display respective values in HTML div如何遍历数组并检查type是连衣裙还是 SweatShirt 并在 HTML div中显示相应的值

Here is an example that will show you how you can loop and assign values to html elements这是一个示例,将向您展示如何循环并为 html 元素分配值

This example is for demonstration only此示例仅用于演示

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据键值对以特定顺序显示 Javascript 数组中的值 - Display values from Javascript array in specific order depending on a key value pair 使用Javascript根据其他键的存在显示JSON值 - Display JSON values depending on presence of other key using Javascript 如何根据值解析json并在HTML表中显示不同的颜色? - How to parse json and display a different color in HTML table depending on value? javascript数组何时可以在key:值对中将元素存储为具有“字符串”值的键? - When can a javascript array store elements in key: value pairs with keys having 'string' values? 如何循环/处理Javascript Key:Value对? - How to loop/process Javascript Key:Value pairs? 将键值对的JSON数组转换为Javascript中的JSON字符串数组 - convert JSON array of key value pairs to JSON Array of strings in Javascript Javascript数组,返回键:具有特定键的值对 - Javascript Array, return key:value pairs with specific key 如何访问数组中的javascript键/值对 - How to access javascript key/value pairs in an array 使用 JavaScript 获取 HTML 表单值并将它们保存到 JSON 键值对中 - Getting HTML form values with JavaScript and saving them into JSON key and value pairs 尝试在对象中的特定键值对上使用 JavaScript 嵌套循环 - Attempting to use a JavaScript nested loop on specific key value pairs in an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM