0

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>

1

1 Answer 1

1

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>

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

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.