按字母顺序排列 JavaScript 对象中的项目?
假设我有一个如下所示的对象:
countrylist:{
regions:[
{
region: "Europe",
countries: [
{
"country":"Albania",
"href":"eu",
"locale":"en_al"
},
{
"country":"France",
"href":"eu",
"locale":"en_fr"
},
{
"country":"Ireland",
"href":"eu",
"locale":"en_ie"
}]
},
region: "Asia",
countries: [
{
"country":"China",
"href":"as",
"locale":"ch"
},
{
"country":"Japan",
"href":"as",
"locale":"jp"
},
{
"country":"Thailand",
"href":"as",
"locale":"th"
}]
}
]}
如果您可以看到整个对象,您会看到它按区域分组,并且每个区域内的国家/地区按字母顺序排序。但是,我需要填充所有国家/地区的下拉菜单(按字母顺序排列),而不是按地区排列。对这些物品进行分类最干净的方法是什么?
我最初将国家/地区字段推入一个空数组并对其进行排序。但是,我需要保留国家/地区字段与其相应的 href 和区域设置字段之间的关系。
Say I have an object that looks like this:
countrylist:{
regions:[
{
region: "Europe",
countries: [
{
"country":"Albania",
"href":"eu",
"locale":"en_al"
},
{
"country":"France",
"href":"eu",
"locale":"en_fr"
},
{
"country":"Ireland",
"href":"eu",
"locale":"en_ie"
}]
},
region: "Asia",
countries: [
{
"country":"China",
"href":"as",
"locale":"ch"
},
{
"country":"Japan",
"href":"as",
"locale":"jp"
},
{
"country":"Thailand",
"href":"as",
"locale":"th"
}]
}
]}
If you could see the whole object, you would see that it's grouped by region, and the countries within each region are sorted alphabetically. However, I need to populate a dropdown menu of all the countries, alphabetized, but not by region. What's the cleanest method to go about sorting these items?
I originally pushed the country field to an empty array and sorted that. However, I need to preserve the relationship between the country field and its corresponding href and locale fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
初始化一个空数组,然后遍历区域并将所有国家/地区附加到该数组中。完成后,对数组进行排序。
http://jsfiddle.net/Jehsb/
Initialize an empty array, then go through the regions and append all the countries to that array. When you're done, sort the array.
http://jsfiddle.net/Jehsb/
您需要遍历您的结构并创建一个国家/地区名称数组。然后你可以对数组进行排序,就完成了。
如果您还需要其他信息,那么您需要的是所有国家/地区对象的平面数组,然后应用自定义排序函数:
You need to walk your structure and create an array of country names. You can then sort the array, and you're done.
If you need the other information as well, what you'd need is a flat array of all country objects, and then apply a custom sort function: