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);
});
});
asked May 6, 2020 at 13:41
user10980228
6371 gold badge10 silver badges23 bronze badges
1 Answer 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>
answered May 6, 2020 at 13:44
palaѕн
74.2k17 gold badges123 silver badges140 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js