3

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note that b.country - a.country would also be possible in the sort function.
Excellent. I knew I needed to push them into their own array but was missing the multi-dimensional facet of things. Thanks for the help!
0
items.sort(function(a, b) {
  if (a.innerHTML < b.innerHTML) return -1;
  else return 1;
});

Add the Country option after the sort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.