我有一个动态数组,可以是空的,或者可以像下面的项目有不同的父项。你永远不会有多少类parent
科目的项目。诀窍是根据父母将项目分组到UL LI列表中
{
"parent": "Vegetables",
"title": "Carrots"
},
{
"parent": "Fruit",
"title": "Apple"
},
{
"parent": "Vegetables",
"title": "Lettuce"
},
{
"parent": "Fruit",
"title": "Banana"
}
这是以下列表的示例
<ul>Fruit
<li>Apple</li>
<li>Banana</li>
</ul>
<ul>Vegetables
<li>Lettuce</li>
<li>Carrots</li>
</ul>
答案 0 :(得分:1)
首先,您应该按照其父名称对项目列表进行分组。然后,遍历分组的项目并将其打印出来。
p / s:您的预期输出结构似乎不正确。
<ul>Fruit</ul>
<li>Apple</li>
<li>Banana</li>
你的意思是:
<ul>
<li>Fruit
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
</li>
</ul>
var items = [{
"parent": "Vegetables",
"title": "Carrots"
}, {
"parent": "Fruit",
"title": "Apple"
}, {
"parent": "Vegetables",
"title": "Lettuce"
}, {
"parent": "Fruit",
"title": "Banana"
}];
var groups = {};
items.forEach(item => {
if (!groups.hasOwnProperty(item.parent)) {
groups[item.parent] = [];
}
groups[item.parent].push(item.title);
});
var result = '';
for (var name in groups) {
result += '<ul>' + name + '</ul>';
groups[name].forEach(item => result += '<li>' + item + '</li>');
}
container.innerHTML = result;
<pre id="container"></pre>
答案 1 :(得分:0)
思考是你想要的解决方案
Script:
<script>
$(document).ready(function(){
var array_list = [{
"parent": "Vegetables",
"title": "Carrots"
},
{
"parent": "Fruit",
"title": "Apple"
},
{
"parent": "Vegetables",
"title": "Lettuce"
},
{
"parent": "Fruit",
"title": "Banana"
}];
var veg = array_list[0].parent;
var fruit = array_list[1].parent;
for(i=0;i<array_list.length;i++){
if(array_list[i].parent == veg){
$(".type").append("<li>"+array_list[i].parent+"</li><li>"+array_list[i].title+"</li>");
}else if(array_list[i].parent == fruit){
$(".type").append("<li>"+array_list[i].parent+"</li><li>"+array_list[i].title+"</li>");
}
}
});
</script>
HTML:
<ul class="type"></ul>
Now by add style to the list as you like.
Hope this is helpful.