Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge JSON Object arrays and sort with Javascript

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.

like image 792
codeisforeva Avatar asked Jun 04 '26 05:06

codeisforeva


1 Answers

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

like image 158
Jordão Avatar answered Jun 06 '26 20:06

Jordão



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!