Expanding Outcome of Iterating through JavaScript JSON Loop

My Javascript loop is encountering an issue. The more IDs there are, the larger the results.

<script>
var jsondata = {"45":    {"id":"45","firstname":"Remy","lastname":"Janssen","age":"32"},"72":{"id":"72","firstname":"Anita","lastname":"Janssen","age":45}};

function display( jsdata ){
    var htmltabel = '';
    for ( var key in jsdata ){
        var datanode = document.createElement("div");
        htmltabel += '<div class="id">' + jsdata[key]['id']    + '</div>';
        content    = htmltabel;
        datanode.innerHTML = content;
        document.getElementById("result").appendChild(datanode);
    }
}
</script>
<div class="result" id="result"></div>
<script>display(jsondata);</script>

The result shown below displays:

<div class="result" id="result">
    <div>
        <div class="id">45</div>
    </div>
<div>
    <div class="id">45</div>
    <div class="id">72</div>
</div>

I am seeking the following desired output:

<div class="result">
    <div class="id">45</div>
    <div class="id">72</div>
</div>

Answer №1

To utilize the datanode you have generated, there is no requirement for an inner div unless you specifically desire one.

<script>
var jsondata = {"45":    {"id":"45","firstname":"Remy","lastname":"Janssen","age":"32"},"72":{"id":"72","firstname":"Anita","lastname":"Janssen","age":45}};

function display( jsdata ){
    for ( var key in jsdata ){
        var datanode = document.createElement("div");
        datanode.className = 'id';
        datanode.innerHTML = jsdata[key]['id'];
        document.getElementById("result").appendChild(datanode);
    }
}
</script>
<div class="result" id="result"></div>
<script>display(jsondata);</script>

Answer №2

It seems like you may be overthinking it, but here's a simpler version that should work for you:

var userData = {
  "45": {
    "id":"45",
    "firstname":"Remy",
    "lastname":"Janssen",
    "age":"32"
  },
  "72": {
    "id":"72",
    "firstname":"Anita",
    "lastname":"Janssen",
    "age":45
  }
};

function showData( data ) {
    for (var key in data) {
        let dataNode = document.createElement("div");
        dataNode.classList.add('user'); // Not sure why this is necessary.
        let text = document.createTextNode(data[key]['id']);
        dataNode.appendChild(text);
        document.getElementById("output").appendChild(dataNode);
    }
}

showData(userData);
<div class="output" id="output"></div>

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

What techniques can be applied to utilize this array without requiring user input?

Today in class, we are diving into the world of arrays. To get a better grasp on them, I am experimenting with the code below using my own array instead of the provided sample. Here is an example of an array: string[16] = {"Sunshine","Moonbeam","Rainbow" ...

Creating a loading spinner in a Vue component while using the POST method

After successfully creating a loader for fetching data using the GET method, I encountered challenges when attempting to do the same with POST method. Is there a reliable way to implement a loader during the POST data process? For GET method, I set the lo ...

Is there a way to customize the checkbox styles and icons in Material-UI React when hovering over them?

Incorporating material-ui into my current project, I've customized a Checkbox to display in red color. My goal is to have the checked Icon appear only when a user hovers over the Checkbox. However, it should remain hidden when not hovered. Unfortunat ...

Utilizing previous ajax call responses for jQuery event handling

In this task, the goal is to retrieve data from the Pokemon API and add it to a list. The API request results contain links to previous and next pages. Here is the HTML structure: <ul class="poke-list"></ul> <div class="pagination"> ...

jQuery - checkboxes behaving like radio buttons

I want to create a group of checkboxes that act like radio buttons, allowing only one selection from the group. Each checkbox will have a different name attribute. How can I achieve this behavior? Solution This feature is important for maintaining consi ...

Encountering a 404 error on Vercel deployment of NextJS

I am currently utilizing a custom express server in conjunction with NextJS. During local development, everything runs smoothly. However, upon deployment to Vercel, I encounter 404 errors when attempting to access my backend API. What could be causing th ...

Queueing up file downloads through a web browser

When trying to download multiple files from a server, I am required to queue them up instead of downloading in parallel. Unfortunately, I do not have access to the download server, so my only option is to work with the browser. Is there an API available t ...

When using a C# Web Service, it may encounter difficulty in producing JSON as an output format,

I'm currently working on implementing jQuery and JSON with a C# Web Service that I created. Despite my best efforts, the code below consistently results in XML output. Webservice Code [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] ...

Using JavaScript and jQuery to create a delay when handling input events

I am working on a project where I have an HTML table that retrieves its values from a database using jQuery Ajax. Here is an example: <div id="tableId"></div> Below is the JavaScript code: function showUser(rowsToShow) { request = $.get("s ...

Rendering JSON data in the browser to display an order

I have discovered that when requesting JSON, the default order cannot be expected. I noticed this while using an API I created where the elements returned were in a random order each time I made a new call. How does a site like Ticketfly's API (you c ...

Listing File Names that are Differ From Each Other

I have successfully implemented the logic in my code and it is working well. However, I am now trying to figure out how to display the names of files that are different between two folders. These file names are stored in the arrays fileNames1 and fileNam ...

Navigating a JSON response within a Spring MVC Controller: A Comprehensive Guide

I have a JSON response that I need to use inside a controller. In my code, I am calling a method that returns the JSON and I would like to loop through the JSON object returned in my controller. I also want to utilize the properties of the JSON object, suc ...

Guide on efficiently removing a user entry from _User via Parse REST API

Having trouble removing a user from the _User table on parse.com and encountering an error. Confident in the correctness of my request syntax, yet receiving the following error: code: 206 error: "Parse::UserCannotBeAlteredWithoutSessionError" Believe th ...

the pop-up modal function is malfunctioning

I can't get my pop up to work properly. When I click the button, the screen dims as if a pop up is going to appear, but nothing shows up. Can someone please assist me with this issue? Here is the HTML file: <!DOCTYPE html> <html lang="en"&g ...

Click on a link to use jQuery to sort the order of the <li>

Looking to rearrange list items by clicking either move up or move down. <div> <ul> <li>Item A <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li> <li>Item B <a class="m ...

What is the best method for importing a basic JSONL file into a PostgreSQL 10 database?

I am working with Postgres version 10 and have a table structured like this Table "musicbrainz.acoustid_meta" Column | Type | Collation | Nullable | Default --------------+-------------------+-----------+----------+------- ...

Generating a List of Countries from a JSON Source

I'm in the process of setting up a dropdown menu with a list of countries in SAP UI5. So far, I've successfully created a combo box with a dynamic list of some countries. However, in order to include more than 100 countries, it seems like the mo ...

Transferring a value via AJAX that has been modified by a previous AJAX call

In my form, users input values which are used to calculate a result. The calculation is performed through AJAX calls triggered by onchange events on the user-edited fields. This process works as expected. However, there is a hidden field that also gets up ...

Integrating Cache and Resolved Promises in Angular's UI-Router: A Comprehensive Guide

I have been working on an Angular app where I used to load all data before displaying any page through the ui-router resolve. However, I found that some data was being repeated, so I decided to cache the data using localStorage. Now I'm trying to figu ...

Setting up a Webpack configuration to compile modules within the node_modules directory

My webpack and babel configuration is causing some issues. I installed my component repository (es6 module without webpack configuration) as a node_module, but it's not working - I'm getting an 'Unexpected token import' error because Ba ...