How can I add the value into my for loop so that my innerHTML displays both key and value? Thank you for your help!
<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>
You can do the one of the following way:
myObj.menu.toppings[key]
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;
<body> <section> <h2>Toppings</h2> <ul id="toppings"> </ul> </section> </body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.