0

) How can i access the Soda object keys and values from this JSON string and get them to display in my innerHTML? What I have here displays the drinks but i need to also display the soda selection...thank you for your help!

<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 Answers 2

1

You need to check for the type of the nested values:

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;
<ul id='drinks'>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

1

First get the soda object.

var soda = myObj.menu.drinks.soda;

then you can get key and value like this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.