Merge JSON Object arrays and sort with Javascript

2020-07-22 17:17发布

问题:

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.

回答1:

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).



回答2:

items.sort(function(a, b) {
  if (a.innerHTML < b.innerHTML) return -1;
  else return 1;
});

Add the Country option after the sort.