将 JavaScript 对象中的项目按字母顺序排列?

Pau*_*dos 3 javascript sorting object

假设我有一个看起来像这样的对象:

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"
                        }]      
                    }
                 ]}
Run Code Online (Sandbox Code Playgroud)

如果你能看到整个对象,你会看到它是按地区分组的,每个地区内的国家都是按字母顺序排序的。但是,我需要填充所有国家/地区的下拉菜单,按字母顺序排列,但不是按地区。对这些物品进行分类的最干净的方法是什么?

我最初将 country 字段推送到一个空数组并对其进行排序。但是,我需要保留 country 字段与其对应的 href 和 locale 字段之间的关系。

Ale*_*pin 5

初始化一个空数组,然后遍历地区并将所有国家/地区附加到该数组中。完成后,对数组进行排序。

var countries = [];
for(var i = 0; i < countrylist.regions.length; i++)
    Array.prototype.push.apply(countries, countrylist.regions[i].countries);

countries.sort(function(a, b) {
    return a.country > b.country;
});

console.log(countries);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Jehsb/