gpt4 book ai didi

javascript - 从 JSON 到分组 ul

转载 作者:行者123 更新时间:2023-12-03 08:18:06 25 4
gpt4 key购买 nike

我有这个带有示例数据的 JSON 变量

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,其中国家/地区位于 sub ul 中

<ul>
<li>Europe
<ul>
<li>Deutschland</li>
<li>....</li>
</ul>
...
</li>

我的想法是创建第二级数组,但我无法创建国家级数组。读取大洲工作正常,但如果我将一个国家/地区插入数组,则会收到错误“插入未定义”这是我的功能:有什么想法或其他方法吗? 函数 getCountries() { var 国家列表 = ""; var 大陆 = 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);

}

最佳答案

您没有在任何地方添加国家/地区。检查 fiddle :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 );
}

关于javascript - 从 JSON 到分组 ul,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com