Error when trying to populate two chained html dropdown objects with JSON data using jQuery?

Tags: , , ,



I am trying to populate two HTML selects with JSON data, but I keep getting this error: Uncaught TypeError: country.map is not a function for the cities. Can someone tell me what’s wrong with this code?

$(document).ready(function() {
  let $country;

  $.getJSON("https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json", function(selectData) {
    function updateSelects() {
      let cities = $.map(selectData[this.value], function(country) {
        let options = [];
        if (country.length > 0) {
          country.map(function(key, val) {
            options.push($("<option />").text(key).val(val));
          });
        }
        return options;
      });
      $("#city").empty().append(cities);
    }
    let state;
    console.log(selectData);
    $country = $("#country").on("change", updateSelects);
    for (state in selectData) {
      $("<option />").text(state).appendTo($country);
    }
    $country.change();
  });
});
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
  <div style="margin: 50px auto; text-align: center;">
    <select id="country" style="font-size: 20px; width: 100px;"></select>
    <select id="city" style="font-size: 20px; width: 100px;"></select>
  </div>
</body>

</html>

Answer

Its because you are mapping twice –

$(document).ready(function() {
  let $country;

  $.getJSON("https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json", function(selectData) {
    function updateSelects() {
      let cities = selectData[this.value].map((key, val) => {
        return $("<option />").text(key).val(val);
      });
      $("#city").empty().append(cities);
    }
    let state;
    console.log(selectData);
    $country = $("#country").on("change", updateSelects);
    for (state in selectData) {
      $("<option />").text(state).appendTo($country);
    }
    $country.change();
  });
});
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
  <div style="margin: 50px auto; text-align: center;">
    <select id="country" style="font-size: 20px; width: 100px;"></select>
    <select id="city" style="font-size: 20px; width: 100px;"></select>
  </div>
</body>

</html>


Source: stackoverflow