开发者

How do I sort this JSON object by the languages on the right of each entry?

I am creating an Android app using PhoneGap and jqTouch, and I have a JSON object containing a word along with a language which that word is in. How can I sort this alphabetically, by the column on the right (the language), using Javascript? The end result should be Afrikaans as the first entry and Zulu as the last.

var languages = {
    "Hello" :   "English",
    "Bonjour"   :   "French",
    "Hola"  :   "Spanish",
    "السّلام عليكم" :   "Arabic",
    "Haai"  :   "Afrikaans",
    "Nei ho"    :   "开发者_如何学编程Cantonese".
    "Goddag"    :   "Danish",
    "Goede dag" :   "Dutch",
    "Saluton"   :   "Esperanto",
    "Hei"   :   "Finnish",
    "Guten tag" :   "German",
    "Gia'sou"   :   "Greek",
    "Aloha" :   "Hawaiian",
    "Hebrew"    :   "Shalom",
    "Namaste"   :   "Hindi",
    "Halo"  :   "Indonesian",
    "Aksunai"   :   "Inuit",
    "Dia dhuit" :   "Irish",
    "Salve" :   "Spanish",
    "Kon-nichiwa"   :   "Japanese",
    "An-nyong Ha-se-yo" :   "Korean",
    "Mandarin"  :   "Ni hao",
    "Hallo" :   "Norweigan",
    "Dzien' dobry"  :   "Polish",
    "Jambo" :   "Swahili",
    "Hej"   :   "Swedish",
    "Sa-wat-dee"    :   "Thai",
    "Merhaba"   :   "Turkish",
    "Vitayu"    :   "Ukrainian",
    "Hylo"  :   "Welsh",
    "Sholem aleychem"   :   "Yiddish",
    "Sawubona"  :   "Zulu"
}

Thanks for your help guys :)


JavaScript does not guarantee any ordering of object properties. So you'll need to create an array which numerically indexes each entry.

E.g.:

var list = [];
for (x in languages) {
  list.push({lang: languages[x], word: x});
}

Then, to sort by language, you can:

list = list.sort(function (a, b) { return a.lang < b.lang; });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜