Reputation: 305
I am trying to populate child object from below json on basis of parent id, but facing some issue, I need your help here. I am new in Json so please suggest me some solution, I wand to show child1, child2 child3 if page id is 2, I am trying to populate child object from below json on basis of parent id, but facing some issue, I need your help here. I am new in Json so please suggest me some solution, I wand to show child1, child2 child3 if page id is 2
[
{
"id": "2",
"slug": "parent",
"title": "Parent",
"subcategories": [
{
"id": "12",
"slug": "child1",
"title": "child1"
},
{
"id": "14",
"slug": "child2",
"title": "child2"
},
{
"id": "15",
"slug": "child3",
"title": "child3"
},
{
"id": "16",
"slug": "child4",
"title": "child4"
}
]
},
{
"id": "11",
"slug": "parent2",
"title": "Parent2",
"subcategories": [
{
"id": "32",
"slug": "child1",
"title": "child1"
},
{
"id": "33",
"slug": "child2",
"title": "child3"
}
]
}
]
[
{
"id": "2",
"slug": "parent",
"title": "Parent",
"subcategories": [
{
"id": "12",
"slug": "child1",
"title": "child1"
},
{
"id": "14",
"slug": "child2",
"title": "child2"
},
{
"id": "15",
"slug": "child3",
"title": "child3"
},
{
"id": "16",
"slug": "child4",
"title": "child4"
}
]
},
{
"id": "11",
"slug": "parent2",
"title": "Parent2",
"subcategories": [
{
"id": "32",
"slug": "child1",
"title": "child1"
},
{
"id": "33",
"slug": "child2",
"title": "child3"
}
]
}
]
$.getJSON("data.json" , function(json) {
$.each(json,function(i, value){
$.each(value.subcategories, function(index, obj){
$('#list-category-slider').append('<div class="item"><a href="/' + obj.slug + '">' + obj.title + '</a></div>');
})
});
});
Upvotes: 0
Views: 101
Reputation: 165
First, filter array to get current page based on id. And iterate over the properties to create the list. For test, pageId is set to 2.
$(function(){
var json =
[
{
"id": "2",
"slug": "parent",
"title": "Parent",
"subcategories": [
{
"id": "12",
"slug": "child1",
"title": "child1"
},
{
"id": "14",
"slug": "child2",
"title": "child2"
},
{
"id": "15",
"slug": "child3",
"title": "child3"
},
{
"id": "16",
"slug": "child4",
"title": "child4"
}
]
},
{
"id": "11",
"slug": "parent2",
"title": "Parent2",
"subcategories": [
{
"id": "32",
"slug": "child1",
"title": "child1"
},
{
"id": "33",
"slug": "child2",
"title": "child3"
}
]
}
]
var pageId = 2;
var currentPage = json.filter(function(el){
return el.id == pageId;
})[0];
$.each(currentPage.subcategories, function(index, obj){
$('#list-category-slider').append('<div class="item"><a href="/' + obj.slug + '">' + obj.title + '</a></div>');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='list-category-slider'>
</div>
Upvotes: 1