Search code examples
jqueryarraysjsonmultidimensional-arraynested-loops

parse Json and create html with similar content


I have a json file and need to generate html of it.

<code>{
    "Exhibitors": {
        "Exhibitor": [
            {
                "LOGO": "logo1.jpg",
                "TYPE": "Exhibitor"
            },
            {
                "LOGO": "logo2.jpg",
                "TYPE": "Exhibitor"
            },
            {
                "LOGO": "logo3.jpg",
                "TYPE": "silver"
            },
            {
                "LOGO": "logo4.jpg",
                "TYPE": "gold"
            }
        ]
    }
}</code>

I need to create 1 list (li) for all the TYPE. and again loop through the json to generate separate divs containing Data of same TYPE.

I am able to generate list using the below code:

<code>
jquery.ajax({
url: "js/sponsors.json",
dataType: "json",
success: function (data) {
        var json = jquery.parseJSON(data);
        var getTYPE = {};
        var items = json.Exhibitors.Exhibitor;
        var types = [];
        var j = 1;
        for (var item, i = 0; item = items[i++];) {
           var type = item.TYPE;
           if (!(type in getTYPE)) {
              getTYPE[type] = 1;
              if (type != "" && type != "Test") {
                  types.push(type);
                  jquery('ul').append('<li id=tab"' + j + '"><a>' + type + '</a> </li>');
                  j++; 
              }
            }
        }
        }
})
</code>

But when looping through the data to segregate the content of similar types, the above code doesn't work. Please suggest a break through.

The HTML Should look like this:

<code>
< ul>
< li>Exhibiotor< /li>
< li>Silver< /li>
< li>Gold< /li>
< /ul>

< div>Exhibitor
  < div>logo1.jpg< /div>
  < div>logo2.jpg< /div>
< /div>

< div>Silver
  < div> logo3.jpg< /div>
< /div>

< div>Gold
  < div> logo4.jpg< /div>
< /div>
</code>

Solution

  • Instead of just putting 1 in getTYPE, make each element an array of all the logos.

        for (var item, i = 0; item = items[i++];) {
           var type = item.TYPE;
           if (!(type in getTYPE)) {
              getTYPE[type] = [item.LOGO];
              if (type != "" && type != "Test") {
                  types.push(type);
                  jquery('ul').append('<li id=tab"' + j + '"><a>' + type + '</a> </li>');
                  j++; 
              }
            } else {
              getTYPE[type].push(item.LOGO);
            }
        }
    

    Then you can loop through getTYPE to make all the DIVs with the logos.

    $.each(getTYPE, function(type, logos) {
        $.each(logos, function(i, logo) {
            ...
        });
    });