1

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);
        });
    });

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.