Skip to content Skip to sidebar Skip to footer

How To Loop Through Jason Data And Display It In Data List Tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array mydata[1] is a multidimensional array, I need to di

Solution 1:

Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.

This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.

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) {
  var content = $("#content");
  firstdata = data[0];
  secdata = data[1];

  for (var i = 0; i < firstdata.length; i++) {
    var dl = $("#content").append("<dl/>");
    dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");

    for (var j = 0; j < secdata.length; j++) {
      if (secdata[i][j] !== undefined) {
        dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
      }
    }
  }
  content.append(dl);
} else {
  console.log('no item for this categories');
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="content"></div>

Post a Comment for "How To Loop Through Jason Data And Display It In Data List Tag (dl)"