Using the .forEach method in JavaScript to convert JSON properties into HTML content

For my project, the JSON data is stored in the variable this.responseText:

{
  'nav': '<a href="">a</a><a href="">b</a>',
  'content': '<div>tartalom</div>',
  'akarmi': 'hello'
}

To efficiently process this data, I plan to utilize a .foreach loop like so:

document.getElementById("nav").innerHTML = '<a href="">a</a><a href="">b</a>';
document.getElementById("content").innerHTML = '<div>tartalom</div>';
document.getElementById("akarmi").innerHTML = 'hello';

Answer №1

If you want to utilize the Object.entries method, you can do so in the following manner:

const data = {
  'nav': '<a href="">a</a><a href="">b</a>',
  'content': '<div>tartalom</div>',
  'example': 'hello'
};

Object.entries(data).forEach(([elementId, html]) => {
  const element = document.getElementById(elementId);
  if(element) element.innerHTML = html;
});
<div id="nav"></div>
<div id="content"></div>
<div id="example"></div>

Answer №2

Success! Shoutout to JSON.parse()

Using Object.entries(JSON.parse(this.responseText)), loop through each element and its HTML content:

Answer №3

index.html

<html>
<head>
<script src="script.js"></script>
</head>
<body onload="javascript:ajax();">
<div id="nav"></div>
<div id="content"></div>
<div id="akarmi"></div>
</body>
</html>

script.js

function ajax () {

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {

        if(this.readyState == 4 && this.status == 200) {

            Object.entries(this.responseText).forEach(([elemId,htmlContent]) => {
                const elem = document.getElementById(elemId);
                if(elem) elem.innerHTML = htmlContent;
            });

        }

    };

    xhttp.open ("GET", "foo.php", true);
    xhttp.send ();

}

foo.php

{
  'nav': '<a href="">a</a><a href="">b</a>',
  'content': '<div>tartalom</div>',
  'akarmi': 'hello'
}

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

Tips on making sure video player controls are always visible on an HTML5 video player

Can anyone help me with my HTML video player? I am trying to make the control bar display always, instead of just when hovered over. Any suggestions? ...

Stop dishonesty in a timed internet assessment

At my company, we frequently host online competitions that involve simple multiple-choice quizzes. The winner is determined by the fastest completion time. Lately, we have been facing a major issue with cheaters submitting quiz entries in less than one se ...

When attempting to bind various data to a single div using knockout js, the issue of duplicate records appearing arises

I am encountering an issue with a div that is set up to display 10 records at a time. When the user clicks on the next link, the next set of 10 records should be loaded from the server. However, after binding the newly added records, they are being shown m ...

Prevent onlick actions until JavaScript function has completed

I run a dynamic quiz website using PHP, JavaScript, and MySQL. The quiz consists of multiple choice questions with answer options displayed on four buttons. <input type = "button" value="$alt1" onClick="changeQuestion('alternative1'); this.st ...

Form data triggering inaccurate results in ajax response

After following online tutorials and seeking help from Stack Overflow, I am still struggling with a strange issue related to AJAX. I appreciate any assistance in solving this problem. I am trying to create a feature where users can search for match result ...

Tips for consistently displaying two decimal points following a period in ReactJS

I am currently working on populating a table in reactjs. One of the columns in the table displays numbers, and I now have a requirement where I need to always show 2 digits after the decimal point.https://i.sstatic.net/ZG6Qv.png For example, as shown in t ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Adding retrieved ejs elements

Aim: I am struggling with a button that triggers a function to fetch more items from my Mongoose DataBase and display them in a table row dynamically. I am using the get method to retrieve data from the server side. Despite referring to advice from this po ...

Retrieve the value of the corresponding array element during the current loop iteration

void main() { var n = 5; var x = 1; var a = [2, 5]; for (x = 1; x <= n; x++) { if (x == a[x]) { // highlighting the values 2 and 5 on 2nd & 5th iteration print(a[x]); } else { print(0); } } } The expected output i ...

Efficient Java JSON parser that eliminates null values in the output

In my small function, I receive an input JSON string which is then parsed using the boon library into a Map. I then update a specific value for a certain key and return the modified JSON string representing the updated Map. Here is the snippet of the code ...

Incorporate a jQuery userscript on Firefox that includes a link to a form

Attempting to incorporate a search link into an online form using a userscript with jQuery, specifically for Firefox. I typically work in Chrome, so I'm encountering some challenges with compatibility in Firefox. However, I need this to be functional ...

How can I create a jumping animation effect for my <li> element in JQuery?

I have a horizontal navigation bar with a "JOIN" option. My goal is to make the #jump item continuously jump up and down after the page has finished loading. Currently, I have this code which only triggers the jump effect once when hovering over the eleme ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

Receiving JSON data from an AJAX request

I am currently facing an issue with my jquery ajax function that successfully retrieves data, however, I am unable to extract individual json data elements from the response using the methods I am familiar with. $("a[name$='-test']").click(funct ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

Displaying a variable in a live HTML user interface

I have successfully created a Python program that captures data from an Arduino Potentiometer and shows it on the Python console. Now, I am working on enhancing the output by displaying it in a local HTML file. I am seeking guidance on how to incorporate t ...

Can you identify the primary parameter used in the Parse.User.signUp() method?

Utilizing Parse.com as the database for my app, I am working on streamlining the code in my signup view. user.set("username",$scope.user.email); user.set("email",$scope.user.email); user.set("password",$scope.user.password); user.signUp(null, ...

Ignore undefined values when parsing JSON with jQuery

I am working with an API that sends back a large JSON response using AJAX. To display this data on my webpage, I use `parse.JSON` and loop through it with jQuery's `$.each` method to append the results to a DOM element. However, I have encountered iss ...

Experiencing difficulties while transferring a json encoded array from php to a js file due to an error message saying "Unexpected end of input."

I am attempting to pass an object array to a JavaScript function every time a button is clicked. <button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button> I have ensured that my JSON data does not contain any ...