Guide to inserting a key and value from a JSON string into innerHTML with JavaScript

Is there a way to incorporate the value into my for loop so that both the key and value are displayed in my innerHTML? Your guidance is much appreciated!

    <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 + ': ' + myObj.menu.toppings[key] + '</li>';
            }
}
var update = document.getElementById('toppings').innerHTML = extras;
</script>

</html>

Answer №1

You have the option to do it in one of the following ways:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a JSON file on Android: A step-by-step guide

I have incorporated a bundled json file into my application for data storage. The aim is to allow users to both read and write data into this json file. The user interface includes a listview displaying existing data from the json file, along with an editt ...

Is there a replacement for findIndex in Internet Explorer?

I am currently working on a code snippet for smooth navigation scroll to different sections. var lastId; var topMenu = $(".community-nav"); var topMenuHeight = topMenu.outerHeight() - 19; if(window.matchMedia("(max-width: 768px)").matches) ...

How can I target only one mapped item when using onClick in React/NextJS?

Apologies if this question is repetitive, but I couldn't find a better way to phrase my issue. The code in question is as follows: const [isFlipped, setFlipped] = useState(false); const flip = () => { if (!isFlipped) { setFlipped(tr ...

Exploring the depths of a JSON data structure

Newbie Alert: I'm dealing with a JSON response that triggers a .on('click') function and it looks like this: {"1411939719-8696.jpeg":true} My goal is to delete a row in a table based on the source of the call, but for some reason, it&apos ...

utilizing PhoneGap for transforming a website into a mobile application

My website is already built and fully functional using ajax, jquery, html, and php. When converting it over to PhoneGap, I'm wondering if I need to create all new php files to attach to the PhoneGap server, or if I can just use the existing files from ...

How can I incorporate a transition into my modal with JavaScript in CSS?

I've recently started learning CSS and while I've come across similar topics, none have provided the solution to my specific problem. After spending 2 hours experimenting with various CSS properties like hidden, transition, and display, I am now ...

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

PHP script automatically resets select option on page load

Consider the following scenario: <form name="limit"> <select name="limiter" onChange="limit(this.value)"> <option selected="selected">&nbsp;</option> <option value="5">5</option> <opti ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Transform your pandas dataframe to JSON, then easily remove single quotes and insert brackets with just a few simple steps!

I successfully converted a pandas dataframe into a JSON string with the addition of 'import_data' at the beginning like this: a = {"import_data" : df.to_json(orient='records')} The resulting output is: {'import_data': &apo ...

If the item already exists within the array, I aim to replace the existing object with the new one

I am faced with a situation where I have an array of objects, and when a user selects an option, it adds a new object to the array. My goal is to write a code that can check if this new object's key already exists in one of the objects within the arra ...

Is there a reason why async functions do not function properly within a controller's get() handler?

Utilizing Node and Express along with the mssql npm package, I establish a connection to an SQL Server database in my app.js file by setting up a global variable that creates a connectionPool (I've excluded some boilerplate code for brevity): const m ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

Tips for decoding and processing multiple JSON objects returned from an AJAX call within the initComponent method of a Sencha Touch panel

Looking for a more efficient way to read multiple JSON objects from an AJAX request. The current code provided below is taking too long, causing other codes to execute before this one. var allVisitStore = new Ext.data.Store({ model: 'allVisit&apos ...

Exploring the extracted data from a JSON file in text format

When making a JSON request to a server, I require access to a time-stamp that will adjust dynamically based on another time variable. Using the requests module, I am sending a post request with the JSON as a .txt file. Here is my JSON data. My goal is to ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...

Resolving ExpressJS routing issues while utilizing AngularJS html5Mode in the context of back4app/Parse-Server

I am currently utilizing the back4app BaaS service which operates on Parse-Server. On the ClientSide, I have integrated AngularJS with html5Mode set to true; The issue I am facing is that this link is not functioning as expected: However, this link works ...

Searching for an array of strings in an express.js application

My concern is related to working with an array of strings. The specific situation involves: let search = ["user","country"]; In order to retrieve data from a MySQL database, I am looking to utilize the LIKE operator. An example of wha ...