A guide to displaying JSON information within a data list element (dl)

I am facing an issue while trying to iterate through a multidimensional json data array. Each time I loop through the array, only the last element gets printed.


var data = [
    [{
            "id": "67",
            "name": "Baby & Toddler Clothing "
        }, {
            "id": "68",
            "name": "Kids' Clothing, Shoes & Accessories"
        }, {
            "id": "69",
            "name": "Costumes, Reenactment Theater"
        }
    ],
    [
        [{
                "id": "572",
                "name": "Baby Clothing Accessories "
            }, {
                "id": "573",
                "name": "Baby Shoes"
            }
        ],
        [{
                "id": "579",
                "name": "Boys Clothing [Sizes 4 & Up] "
            }, {
                "id": "580",
                "name": "Boys Shoes"
            }
        ],
        [{
                "id": "588",
                "name": "Costumes"
            }, {
                "id": "589",
                "name": "Reenactment & Theater "
            }
        ]
    ]
];

if (data.length > 0) {
    firstdata = data[0];
    secdata = data[1];
    for (var i = 0; i < firstdata.length; i++) {
        level_1 = firstdata[i].name;
        level_1_id = firstdata[i].id;
        for (var j = 0; j < secdata.length; j++) {
            if (secdata[i][j] !== undefined) {
                level_2 = '';
                level_2 = secdata[i][j].name;
                level_2_id = secdata[i][j].id;
            }

            console.log(level_2);

        }

        var dldata = $(
            '<dl>' +
            "<dt href='" + level_1_id + "'>" + level_1 + "</dt>" +
            "<dd href='" + level_2_id + "'>" + level_2 + "</dd>" +
            '</dl>'
        );

        $("#content").html(dldata);
    }

} else {
    console.log('no item for this categories');
}

After running the code, I noticed that only the last element in the array was printed, as shown in this fiddle.

The fiddle displays Costumes, Reenactment Theater, and Reenactment & Theater which are the last elements of each json array mentioned above.

The expected output should be:

Baby & Toddler Clothing
   Baby Clothing Accessories
   Baby Shoes

Kids' Clothing, Shoes & Accessories
   Boys Clothing [Sizes 4 & Up]
   Boys Shoes

Costumes, Reenactment Theater
   Costumes
   Reenactment & Theater

However, I only got:

Costumes, Reenactment Theater
   Costumes

I hope this clarifies my question and appreciate any help in advance.

Answer ā„–1

The reason for this issue is that the initial loop clears the content of your content div with each iteration. To rectify this, consider using the following code:

$("#content").append(dldata);

By implementing this change, you ought to observe the expected display of all three outputs.

Answer ā„–2

If you're looking to quickly try out this code snippet (which will need some refactoring), here's the sample code:

var data = [


[{
      "id": "67",
      "name": "Baby & Toddler Clothing "
  }, {
      "id": "68",
      "name": "Kids' Clothing, Shoes & Accessories"
  }, {
      "id": "69",
      "name": "Costumes, Reenactment Theater"
  }],
  [
    [{
        "id": "572",
        "name": "Baby Clothing Accessories "
    }, {
        "id": "573",
        "name": "Baby Shoes"
    }],
    [{
        "id": "579",
        "name": "Boys Clothing [Sizes 4 & Up] "
    }, {
        "id": "580",
        "name": "Boys Shoes"
    }],
    [{
        "id": "588",
        "name": "Costumes"
    }, {
        "id": "589",
        "name": "Reenactment & Theater "
    }]
  ]


 ]



if (data.length > 0) {
  firstdata = data[0];
  secdata = data[1];
  result = '<dl>';
  firstdata.map((firstD, i) => {
    result += "<dt href='" + firstD.id + "'>" + firstD.name + "</dt>";
    secdata[i].map(secD => result += "<dd href='" + secD.id + "'>" + secD.name + "</dd>");
    
    });
result += '</dl>';


    console.log(result);


} else {
  console.log('no item for this categories');
}

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

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Ways to receive a POST request from an external server on a GraphQL Server

Currently, I am working on a project that utilizes GraphQL. As part of the project, I need to integrate a payment processor. When a user makes a successful payment, the payment processor sends a POST request to a webhook URL that should point to my server. ...

Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a table view. import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOu ...

Value binding in Angular being passed to ng-click function rather than the actual value

An HTML link is causing me some trouble: <div class="menu-item" ng-repeat="pageName in pages"> <a ng-click="routing.open('{{pageName}}')">{{pageName}}</a> </div> When clicked, this link triggers the 'open' ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

Tips for showing a single table with buttons on display

I am using R markdown and have included multiple tables with buttons, but when I open the file, all tables are displayed at once. How can I ensure only one table is shown upon opening the file? https://i.sstatic.net/NFidf.png <script type="text/ja ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

Fade in elements from an array using jQuery

Hey there, I'm currently facing an issue with using Javascript to process data within a function. Since I'm new to Javascript, I'm hoping for a simple explanation. My aim is to display each item from an array sequentially, with a fading in ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

JQueryMobile 1.3.2 encounters issues with popups following the installation of Chrome version 43.0.2357.65 m update

Is anyone else experiencing issues with the latest version of Chrome "43.0.2357.65 m" causing problems with JQueryMobile 1.3.2? When I try to click on a popup, it suddenly jumps to the top of the page and the scroll bar disappears. This was not an issue in ...

Transformation of firebug console information into a function()

Snippet of JavaScript code: KT_initKeyHandler(b) Firebug console output: KT_initKeyHandler(b=keydown charCode=0, keyCode=90) Corresponding JavaScript function call: KT_initKeyHandler(?) Example: Snippet of JavaScript code: KT_event(b,c) Firebug ...

What sets babel.config.js apart from vue.config.js and is it possible to merge both files together?

When setting up my Vue application using the Vue cli, I noticed that there was already a babel.config.js file in the directory created by the cli. However, I also added a vue.config.js file. Iā€™m curious about the difference between these two files and wh ...

What is the process for modifying the logfile path in phantomjs using selenium?

Is there a way to modify the default --webdriver-logfile parameter that selenium passes to phantomjs when using them together? This is the line in the selenium log: 11:06:06.960 INFO - arguments: [--webdriver=14380, --webdriver-logfile=<ROOT PATH DELE ...

What is the process for combining two values from a JSON-array in a specific sequence?

Currently, I am utilizing PostgreSQL 9.5 and have a table containing JSON arrays with JSON objects structured like so: [] [{animal:cat}, {plant:sunflower}, {car:mercedes}] [{animal:dog}] [{animal:dog}, {car:audi}] [] The goal is to present a table that m ...

problem with sending JSON data as a string

I am trying to send a property of type 'string' to a WCF server. The string will contain JSON data, but I keep encountering this error: The server has encountered an error while processing the request. The exception message is 'There was an ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...