Search code examples
javascripthtmlajax

Populate a list of countries data stored in JSON file in a HTML drop down box. PHP/JavaScript/AJAX - getting double values and unsorted


I am new here so I do beg your pardon if I sound base.

I am trying to create a dropdown box in HTML to populate a list of countries stored in a JSON file. The name of the countries are found in an object within another object in an array which is in an object.

I have managed to populate the countries within the dropdown box but they appear duplicated and are not in alphabetical order.

I tried using .sort() but not sure how without breaking my code.

index.html

<span id="selectContainer">
  <select name="country" id="country" class="form-select">
    <!-- populate from PHP call that returns only the codes and names from the countryborder GeoJSON file -->
    <option value="">Select a country</option>
  </select>
</span>

script.js

$.getJSON("./countryBorders.geo.json", function (data) {
    const result = data['features'];

    for (let i = 0; i < result.length; i++) {
        let name = result[i]['properties']['name'];

        $.each(data, function (key, item) {
            $('#country').append(
                $('<option></option>')
                    .val(item)
                    .html(name)
            );
        })
    }
});

A sample of the JSON file known as countryBorders.geo.json:

{"type": "featureCollection", "features": 
[{"type": "Feature", "properties": {"name": Bahamas", "iso_a2":"BS", "iso_a3": "044"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]}, 
{"type": "Feature", "properties": {"name": Mexico", "iso_a2":"MX", "iso_a3": "484"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]},
{"type": "Feature", "properties": {"name": Trinidad and Tobago", "iso_a2":"TT", "iso_a3": "780"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]}, 
...

and so forth:
Picture of what my dropdown box looks like

Any suggestions will be greatly appreciated!
Thanks in anticipation!


Solution

  • You could achieve it like this:

    <span id="selectContainer">
      <select name="country" id="country" class="form-select">
        <option value="">Select a country</option>
      </select>
    </span>
    

    And your script:

    $.getJSON("./countryBorders.geo.json", function(data) {
      const result = data['features'];
      let countryNames = [];
    
      // Populate the countryNames array
      for (let i = 0; i < result.length; i++) {
        let name = result[i]['properties']['name'];
        countryNames.push(name);
      }
    
      // Sort the country names
      countryNames.sort();
    
      // Populate the dropdown
      for (let i = 0; i < countryNames.length; i++) {
        $('#country').append(
          $('<option></option>')
            .val(countryNames[i])
            .html(countryNames[i])
        );
      }
    });