2

I want to list Categories and inside each category I want to list subcategories, so I am running loop inside a loop like this, but unfortunately it is returning me like this:

Category(Mobile)
Category(Laptop)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)

But what I want is some think like this:

Category(Mobile)
Subcategory(Iphone4)
Subcategory(Iphone5)
Subcategory(Iphone6)
Category(Laptop)
Subcategory(dell1)
Subcategory(dell2)
Subcategory(dell3)

Here is my code:

$(document).ready(function()
         {
              var url="https://myjson";
              $.getJSON(url,function(result){
                   $.each(result, function(i, field){
                        var categoryId=field.categoryId;
                        var categoryName=field.categoryName;
                        $("#listview").append("<h3>"+ categoryName + "</h3>");
                        $.each(field.subcategories, function(i, row){
                             var id=row.subCategoryId;
                             var subCategoryName=row.subCategoryName;
                             $("#listviewchild").append("<p>"+ subCategoryName + "</p>");
                        });
                   });
              });
         });
   <div class="container-fluid">
    
     <div id="listview">
     </div>
     <div id='listviewchild'>
     </div>
    </div>

1 Answer 1

4

Basically, from your code, your category will always append on the above of your subcategory based on the html that u have.

Here`s the logic that will append as what you need

javascript

 $(document).ready(function()
         {
              var url="https://myjson";
              $.getJSON(url,function(result){
                   $.each(result, function(i, field){
                        var categoryId=field.categoryId;
                        var categoryName=field.categoryName;
                        $("#listview").append("<h3>"+ categoryName + "</h3>");
                        $.each(field.subcategories, function(i, row){
                             var id=row.subCategoryId;
                             var subCategoryName=row.subCategoryName;
                             $("#listview").append("<p>"+ subCategoryName + "</p>");
                        });
                   });
              });
         });

html

   <div class="container-fluid">

     <div id="listview">
     </div>
    </div>
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh Thanks alot it worked, I knew that i have a problem with my code but was not able to find correct logic

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.