使用Javascript按字母顺序对JSON响应进行排序 [英] Sort JSON response alphabetically using Javascript
本文介绍了使用Javascript按字母顺序对JSON响应进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
服务器从查询返回以下响应:
The server returns the following response from a query:
{ ROM: "Romania",
YUG: "Yugoslavia",
PRT: "Portugal",
MKD: "Macedonia",
GRC: "Greece",
FRA: "France",
ISL: "Iceland",
LUX: "Luxembourg",
HUN: "Hungary",
GBR: "United Kingdom", 36 more… }
我需要将它们放入一个已经存在的选择中,像这样:
I need to put these into an already existing select like so:
$.each(result, function(key, value) {
$('#country')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
有人可以告诉我在将国家/地区插入html元素之前如何按字母顺序对国家/地区进行排序吗?
Can someone tell me how to sort the countries alphabetically by value before inserting them into the html element?
推荐答案
您不能对对象进行排序,但是可以对数组进行排序,因此可以创建一个由HTMLOptionElement
个对象组成的数组并对其进行排序,然后将其附加到选择中元素.
You can't sort objects but you can sort arrays, so you can create an array of HTMLOptionElement
objects and sort it and then append it to the select element.
$('#country').append(function() {
return $.map(result, function (key, value) {
return new Option(key, value);
}).sort(function (a, b) {
return a.text.localeCompare(b.text);
});
});
这篇关于使用Javascript按字母顺序对JSON响应进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文