我有一个嵌套的对象数组,如下所示:
result = [
[{"country":"France","continent":"Europe","name":"street a"}],
[{"country":"Brazil","continent":"South America", "name":"street b"},{"country":"Brazil","continent":"South America", "name":"street c"}],
[{"country":"Germany","continent":"Europe","name":"street d"}]
]
请注意,这是在使用大洲键和国家键排序后从对象数组生成的。
我想动态生成如下列表(大陆和国家)并将其添加到 div
:
- 欧洲
- 法国
- 街道a
- 德国
- 街道d
- 法国
- 南美洲
- 巴西
- b街
- 街道c
- 巴西
每次返回的国家和大陆都会不同,但结果数组会按大陆、国家顺序分组。
因为我是 HTML、CSS 和 JavaScript 的新手,所以我不知道如何动态创建这个列表。到目前为止,我已经成功地生成了一个唯一的大陆列表,使用:
for(var i=0;i<result.length;i++){
if($('#continent-list li').filter(function(){
return $(this).text() == result[i][0].continent;
}).length == 0){
$('#continent-list').append('<li>'+result[i][0].continent+'<ul></ul></li>');
}
即,我遍历列表,只费心去查看第一个元素 [result[i][0]) 并将其添加到名为“continent-list”的无序列表中。每次我还检查该名称是否已存在于无序列表中,如果不存在,我才添加。
最佳答案
我认为一种方法是遍历数组中的对象并为可用的大陆创建 div,同时确保没有大陆被创建超过一次然后仍然使用相同的循环你可以使用像
for(i=0;i<=results.length;i++){
if (result[i].continent == continent) //here talking about the present continent in the main loop{
//code to create new div for the current country....then same procedure for the street part....
}
}
抱歉,我听起来不太像 jqueryish :D 但我真的希望你明白这一点
关于javascript - 使用对象数组动态创建分组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811843/