我有这个带有示例数据的JSON var
var data = { "destinations":[
{
"Hotel":"Hotel Waldorf",
"Country":"BR",
"Continent":"South America",
"City": "City",
"Link" : ""
},
{
"Hotel":"Hilton",
"Country":"CR",
"Continent":"Middle America",
"City": "San Jose",
"Link" : ""
},
{
"Hotel":"Park Inn",
"Country":"DE",
"Continent":"Europe",
"City": "Berlin",
"Link" : "http://www.typo3.org"
},
{
"Hotel":"Michelsberger",
"Country":"DE",
"Continent":"Europe",
"City": "Berlin",
"Link" : "http://www.berlin.de"
}
]}
我想要一个按大陆分组的ul和子ul的国家/地区
<ul>
<li>Europe
<ul>
<li>Deutschland</li>
<li>....</li>
</ul>
...
</li>
我的想法是创建一个二级数组,但我不能创建国家级别。阅读大陆工作正常,但如果我推动一个国家到阵列,我得到一个错误“推到未定义” 这是我的功能: 任何想法或其他方式? function getCountries(){ var countryList =“”; var continents = new Array();
for (var i in data.destinations) {
if ( $.inArray(data.destinations[i].Continent , continents) == -1) {
continents.push(data.destinations[i].Continent);
} else {
}
}
continents.sort();
for (var j in continents) {
countryList += "<li>"+continents[j]+"</li>";
}
countryList += "</ul>";
$('#js--fx--country-list').html(countryList);
}
答案 0 :(得分:1)
您不是在任何地方添加国家/地区。 检查小提琴:JS Fiddle
您的脚本可能如下所示(我注释掉了一些代码):
function getCountries() {
var continents = [],
//countryList = '',
continentsObj = {},
html = '',
continent,
country;
for (var i in data.destinations) {
//if ( $.inArray(data.destinations[i].Continent , continents) == -1) {
// continents.push(data.destinations[i].Continent);
// check if continent exists
continent = data.destinations[i].Continent;
if (!continentsObj[ continent ]) {
continentsObj[ continent ] = [];
// also add to smiple array to sort later
continents.push(continent);
}
// check if country exists
country = data.destinations[i].Country;
if ( continentsObj[ continent ].indexOf( country ) === -1 ) {
continentsObj[ continent ].push( country );
}
}
continents.sort();
html += '<ul>';
for (var i=0, lenI=continents.length; i<lenI; i++) {
continent = continents[i];
html += '<li>'+continent;
html += '<ul>';
for (var y=0, len = continentsObj[ continent ].length; y<len; y++) {
html += '<li>'+continentsObj[ continent ][y]+'</li>';
}
html += '</ul>';
html +='</li>';
}
html += '</ul>';
$('#js--fx--country-list').html( html );
}