如何使用JavaScript

时间:2018-03-08 02:45:38

标签: javascript json innerhtml

)如何从这个JSON字符串访问Soda对象键和值并让它们显示在我的innerHTML中?我在这里展示的是饮料,但我还需要显示苏打水的选择......谢谢你的帮助!

<script>
var selection ='{"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 myObj = JSON.parse(selection)
var extras ="";
var key="";
    var beverages ="";
    for(key in myObj.menu.drinks){
        if (myObj.menu.drinks.hasOwnProperty(key)) {
            beverages +='<li>' +
            key + ':' + myObj.menu.drinks[key] +  '</li>';
                }
    }

var update = document.getElementById('drinks').innerHTML = beverages;
</script>

2 个答案:

答案 0 :(得分:1)

您需要检查嵌套值的类型:

&#13;
&#13;
var selection ='{"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 myObj = JSON.parse(selection)
var extras ="";
var key="";
    var beverages ="";
    for(key in myObj.menu.drinks){
        if (myObj.menu.drinks.hasOwnProperty(key)) {        
            if (typeof myObj.menu.drinks[key] === 'string') {
              beverages +='<li>' +
              key + ':' + myObj.menu.drinks[key] +  '</li>';               
            } else {
            beverages +='<li>' + key + '</li>'; 
              
              beverages += '<ul>';
              for(var ikey in myObj.menu.drinks[key]){
                if (myObj.menu.drinks[key].hasOwnProperty(ikey)) {
                  beverages +='<li>' +
                    ikey + ':' + myObj.menu.drinks[key][ikey] + '</li>';
                }
              }
              beverages += '</ul>';
            }
        }
    }

var update = document.getElementById('drinks').innerHTML = beverages;
&#13;
<ul id='drinks'>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先得到苏打水对象。

var soda = myObj.menu.drinks.soda;

然后你可以获得这样的关键和价值。

Object.keys(soda).forEach( key => console.log(key, soda[key]));