在Json中填充子对象

时间:2017-08-17 18:34:46

标签: javascript jquery arrays json

我试图根据父ID在json下面填充子对象,但面对一些问题,我需要你的帮助。我是Json的新手所以请建议我一些解决方案,如果页面ID为2,我想显示child1,child2 child3,我试图根据父ID在json下面填充子对象,但是面对一些问题,我需要你在这里帮忙。我是Json的新手所以请给我一些解决方案,如果页面ID为2,我会向我展示child1,child2 child3

# cat Dockerfile 
...
ADD init.sql /tmp
ADD initdb.sh /tmp
RUN /tmp/initdb.bash
CMD ["/usr/bin/mysqld_safe --datadir=/var/lib/mysql"]

1 个答案:

答案 0 :(得分:1)

首先,过滤数组以获取基于id的当前页面。并遍历属性以创建列表。对于测试,pageId设置为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>