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>

kboul
14.7k5 gold badges50 silver badges60 bronze badges
asked Nov 3, 2017 at 7:27

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>
answered Nov 3, 2017 at 7:34
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.