jQuery 使用jQuery根据值对JSON数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18490135/
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
Sort JSON array based on value with jQuery
提问by davey
I've got two dropdown select dropdowns: one for regions and one for cities in the selected region. The result is loaded by AJAX and in my response i get all cities in an JSON array:
我有两个下拉选择下拉列表:一个用于区域,一个用于所选区域的城市。结果由 AJAX 加载,在我的响应中,我得到了 JSON 数组中的所有城市:
{
1709: "Geertruidenberg",
1710: "Netersel",
1711: "Macharen",
1712: "Beers",
1713: "Hank",
1714: "Oudemolen",
1715: "Nistelrode"
}
I'm using this small plugin to load the data in the select dropdown:
我正在使用这个小插件在选择下拉列表中加载数据:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", index)
.text(option);
self.append($option);
});
};
})(jQuery, window);
And this piece of javascript to do the AJAX request:
这段 javascript 来执行 AJAX 请求:
$('select#Profile_regionId').change(function() {
$.post('/ajax/getcities', {regionid: $(this).val()}, function(data){
//console.log(data.cities);
$("select#Profile_cityId").replaceOptions(data.cities);
}, 'json');
});
All works totally fine, except the city dropdown is automatically sorted on the JSON array key. I tried to use the sort() method for this, but it won't work because it's an Object and not an array. Then i tried to create an array of it:
一切正常,除了城市下拉列表自动按 JSON 数组键排序。我尝试为此使用 sort() 方法,但它不起作用,因为它是一个对象而不是数组。然后我尝试创建一个数组:
var values = [];
$.each(data.cities, function(index,value)) {
values[index] = value;
}
But for some reason, the dropdown list fills itself up from 1 to the first found id (key of array) of the city, and i don't know why it's doing that (array itself looks fine).
但出于某种原因,下拉列表将自身从 1 填充到城市的第一个找到的 id(数组的键),我不知道它为什么这样做(数组本身看起来不错)。
How can i sort the thing so my cities are ordered alphabetically in the dropdown list?
如何对事物进行排序,以便我的城市在下拉列表中按字母顺序排列?
回答by Brigand
It needs to be converted to an array so that it can be sorted. Let's assume this is your object. Note that I rearranged it to be unsorted, to prove this works.
需要将其转换为数组,以便对其进行排序。让我们假设这是您的对象。请注意,我将其重新排列为未排序,以证明这是有效的。
originalData = {
1712: "Beers",
1709: "Geertruidenberg",
1710: "Netersel",
1713: "Hank",
1714: "Oudemolen",
1711: "Macharen",
1715: "Nistelrode"
};
Now to create an array version we need to create an array, and insert objects into it. I'm calling the keys "year". Note that we're calling parseInt on the keys. Keys in JavaScript (except for arrays) are always strings. For example, {foo: "bar"}
has a string key "foo". This also applies to numerical looking keys.
现在要创建一个数组版本,我们需要创建一个数组,并将对象插入其中。我称这些键为“年”。请注意,我们在键上调用 parseInt。JavaScript 中的键(数组除外)始终是字符串。例如,{foo: "bar"}
有一个字符串键“foo”。这也适用于数字键。
var dataArray = [];
for (year in originalData) {
var word = originalData[year];
dataArray.push({year: parseInt(year), word: word});
}
There's a chance that we have our data out of sort right now, so we manually sort it. Note that this is a case sensitive sort. For example, "Qux" comes before "foo".
我们现在有可能对数据进行排序,因此我们手动对其进行排序。请注意,这是区分大小写的排序。例如,“Qux”在“foo”之前。
dataArray.sort(function(a, b){
if (a.word < b.word) return -1;
if (b.word < a.word) return 1;
return 0;
});
The function now just pulls option.year and option.word from our array.
该函数现在只从我们的数组中提取 option.year 和 option.word 。
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.year)
.text(option.word);
self.append($option);
});
};
And then you finally use the plugin, passing the array. You can put all of this code inthe plugin, if that works best for you.
然后你终于使用了插件,传递了数组。如果最适合您,您可以将所有这些代码放在插件中。
$('#mylist').replaceOptions(dataArray);
fiddle
小提琴
回答by Floris
This will do what you want and take care of the empty ids/undefined values:
这将执行您想要的操作并处理空 ID/未定义值:
var data = {
1709: "Geertruidenberg",
1710: "Netersel",
1711: "Macharen",
1712: "Beers",
1713: "Hank",
1714: "Oudemolen",
1715: "Nistelrode"
};
var values = [];
$.each(data, function(index, value) {
values[index] = value;
});
values.sort();
$.each(values, function(index, value) {
if(value != undefined) {
$("#Profile_cityId").append("<option>"+ value +"</option");
}
});
Just replace the append I put in with your own function because jsFiddle was giving me trouble using that. Demo: http://jsfiddle.net/R4jBT/3/
只需将我放入的 append 替换为您自己的函数,因为 jsFiddle 使用它给我带来了麻烦。演示:http: //jsfiddle.net/R4jBT/3/