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"]
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>');
});
});
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>
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 });
}
}
Then you sort it:
countries.sort(function(a, b) {
if (a.country < b.country) return -1;
if (a.country > b.country) return 1;
return 0;
});
And then you use it:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With