合并JSON对象数组并使用Javascript进行排序 [英] Merge JSON Object arrays and sort with Javascript
问题描述
我有一个包含12个数组的JSON对象。不同地区的国家。我正在尝试将此数组合并到选择下拉菜单中。 JSON看起来像这样:
I have a JSON object with 12 arrays. Different regions of countries. I'm trying to merge this array into select dropdown menu. The JSON looks like this:
"latinamerica": [
"Argentina",
"Bolivia",
"Brazil",
"Chile",
"Colombia",
"Ecuador",
"Paraguay",
"Peru"
],
"korea": ["South Korea"]
然后我打电话在JSON中:
Then I call in the JSON with:
$.getJSON('js/countries.json', function(data) {
var items = [];
items[0] = '<option value="0">Country</option>';
$.each(data['latinamerica'], function(key, val) {
items.push('<option value="'+ key +'">'+ val +'</option>');
});
});
对Object中的每个数组执行此操作。问题是我想合并所有这些数组,按字母顺序对它们进行排序,但仍保持它们所关联的区域。所以基本上我会有一个所有国家的下拉列表,HTML看起来像:
Doing this for every array in the Object. Problem is I want to merge all these arrays, sort them alphabetically but still maintain what region they are associated with. So essentially I would have a dropdown of all the countries and the HTML would look like:
<option value="latinamerica">Argentina</option>
<option value="europe">Austria</option>
我尝试过连接但后来丢失了我的数组名称。建议? TIA。
I've tried doing concat but then I lose my array names. Suggestions? TIA.
推荐答案
您基本上需要一个不同的模型来生成视图:
You basically need a different "model" to generate that "view":
var countries = [];
for (var region in data) {
for (var i = 0, l = data[region].length; i < l; ++i) {
countries.push({ country: data[region][i], region: region });
}
}
然后你对它进行排序:
countries.sort(function(a, b) {
if (a.country < b.country) return -1;
if (a.country > b.country) return 1;
return 0;
});
然后你使用它:
var items = [];
items.push('<option value="0">Country</option>');
for (var i = 0, l = countries.length; i < l; ++i) {
items.push('<option value="'+ countries[i].region +'">'+ countries[i].country +'</option>');
}
(注意:所有这些代码都是未经测试的) 。
(NOTE: all this code is untested).
这篇关于合并JSON对象数组并使用Javascript进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!