jQuery Javascript 按值对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12982201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Sort Array by Value
提问by Fluidbyte
I have an AJAX call returning JSON like...
我有一个 AJAX 调用返回 JSON,例如...
{
490: "A",
675: "B",
491: "C",
520: "D",
681: "E",
679: "F",
538: "G"
}
I then have it appending to a select
using:
然后我将它附加到select
使用:
var output = jQuery.parseJSON(data);
$.each(output, function(key, value) {
$el.append($("<option></option>")
.attr("value", key).text(value));
});
I'd like to sort by the value so the output is A,B,C,D...
as right now it just reads in order of the key.
我想按值排序,所以输出A,B,C,D...
就像现在一样,它只是按键的顺序读取。
Here's the kicker- seems to work fine in Firefox, not in Chrome.
这是踢球者- 似乎在 Firefox 中工作正常,而不是在 Chrome 中。
回答by Anoop
first convert it into array, sort it, then create html. jsfiddle
首先将其转换为数组,对其进行排序,然后创建 html。提琴手
var output = jQuery.parseJSON(data);
var temp = [];
$.each(output, function(key, value) {
temp.push({v:value, k: key});
});
temp.sort(function(a,b){
if(a.v > b.v){ return 1}
if(a.v < b.v){ return -1}
return 0;
});
$.each(temp, function(key, obj) {
$el.append($("<option></option>")
.attr("value", obj.k).text(obj.v));
});
回答by Kevin B
Objects cannot be sorted. Try returning your JSON as an array to ensure it stays in the exact order that you return them in:
对象无法排序。尝试将您的 JSON 作为数组返回,以确保它保持在您返回它们的确切顺序中:
[
{"id":490,"name":"A"},
{"id":675,"name":"B"},
{"id":491,"name":"C"},
{"id":520,"name":"D"},
{"id":681,"name":"E"},
{"id":679,"name":"F"},
{"id":538,"name":"G"}
]
Here's a fiddle with the original: http://jsfiddle.net/82BSm/2/and changing to an array: http://jsfiddle.net/82BSm/1/
这是原始的小提琴:http: //jsfiddle.net/82BSm/2/并更改为数组:http: //jsfiddle.net/82BSm/1/
Updated per pst's comment
根据 pst 的评论更新
You could of course make the json response size smaller by separating the column names ("id" and "name") from the data and making it an array of arrays.
您当然可以通过将列名(“id”和“name”)与数据分开并使其成为数组数组来减小 json 响应大小。
回答by David Sanders
How about something like this?
这样的事情怎么样?
var output = jQuery.parseJSON(data);
var options = [];
$.each(output, function(key, value) {
options.push(
$("<option>").val(key).text(value)
);
});
options.sort(function(a, b) {
return a.text() > b.text();
});