如何使用JavaScript将JSON字符串中的键和值添加到innerHTML中

时间:2018-03-07 03:52:57

标签: javascript json innerhtml

如何将值添加到for循环中,以便我的innerHTML同时显示键和值?谢谢你的帮助!

    <body>

<section>
<h2>Toppings</h2>
<ul id="toppings">    </ul>
</section>

     </body>
<script>
var myObj ={"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},   "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};
var extras ="";
for(key in myObj.menu.toppings){
    if (myObj.menu.toppings.hasOwnProperty(key)) {
        extras +='<li>' +
        key + '</li>';
            }
}
var update = document.getElementById('toppings').innerHTML = extras;
</script>

</html>

1 个答案:

答案 0 :(得分:2)

您可以采用以下方式之一:

myObj.menu.toppings[key]

&#13;
&#13;
var myObj = {
  "menu": {
    "slice of pizza": "2.00",
    "toppings": {
      "pepperoni": ".25",
      "meatballs": ".35",
      "mushrooms": ".40",
      "olives": ".20"
    },
    "sides": {
      "potato salad": "1.25",
      "hummus": "2.50",
      "caesar salad": "3.50",
      "garden salad": "2.25"
    },
    "drinks": {
      "soda": {
        "small": "1.95",
        "medium": "2.20",
        "large": "2.50"
      },
      "juice": "2.00",
      "water": "1.25"
    }
  }
};

var extras = "";

for (key in myObj.menu.toppings) {
  if (myObj.menu.toppings.hasOwnProperty(key)) {
    extras += '<li>' +
      key+':'+myObj.menu.toppings[key] + '</li>';
  }
}

var update = document.getElementById('toppings').innerHTML = extras;
&#13;
<body>
  <section>
    <h2>Toppings</h2>
    <ul id="toppings"> </ul>
  </section>
</body>
&#13;
&#13;
&#13;