user10980228
user10980228

Reputation: 637

How to loop through a nested array with jQuery

This is how I would access the 1st item in the array, so there is a sub category array inside the categories array.

    console.log(data.Body.Categories[0].CategoryName);
    console.log(data.Body.Categories[0].SubCategories[0].CategoryName);

I am trying to do something like this but it still only shows the parent categories and not the sub categories.

    jQuery.each(data.Body.Categories, function(index, value) {
        console.log(value.CategoryName);
        jQuery.each(data.Body.Categories.SubCategories, function(key, val) {
            console.log(val.CategoryName);
        });
    });

Upvotes: 1

Views: 113

Answers (1)

palaѕн
palaѕн

Reputation: 73966

You can simply do this by replacing this inside 2nd loop:

data.Body.Categories.SubCategories

with this:

value.SubCategories

as value here represents each object inside Categories array.

So, full code will be like:

jQuery.each(data.Body.Categories, function(index, value) {
    console.log('CategoryName: ', value.CategoryName);
    jQuery.each(value.SubCategories, function(key, val) {
        console.log('Sub-CategoryName: ', val.CategoryName);
    });
});

Demo:

const Categories = [
  {
    CategoryName: 'A',
    SubCategories: [
      {CategoryName: 'A1'}, {CategoryName: 'A2'}
    ]
  },
  {
    CategoryName: 'B',
    SubCategories: [
      {CategoryName: 'B1'}, {CategoryName: 'B2'}
    ]
  }
]


jQuery.each(Categories, function(index, value) {
  console.log('CategoryName: ', value.CategoryName);
  jQuery.each(value.SubCategories, function(key, val) {
    console.log('Sub-CategoryName: ', val.CategoryName);
  });
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions