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?
JavaScript
x
25
25
1
$(document).ready(function() {
2
let $country;
3
4
$.getJSON("https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json", function(selectData) {
5
function updateSelects() {
6
let cities = $.map(selectData[this.value], function(country) {
7
let options = [];
8
if (country.length > 0) {
9
country.map(function(key, val) {
10
options.push($("<option />").text(key).val(val));
11
});
12
}
13
return options;
14
});
15
$("#city").empty().append(cities);
16
}
17
let state;
18
console.log(selectData);
19
$country = $("#country").on("change", updateSelects);
20
for (state in selectData) {
21
$("<option />").text(state).appendTo($country);
22
}
23
$country.change();
24
});
25
});
JavaScript
1
14
14
1
<html>
2
3
<head>
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
5
</head>
6
7
<body>
8
<div style="margin: 50px auto; text-align: center;">
9
<select id="country" style="font-size: 20px; width: 100px;"></select>
10
<select id="city" style="font-size: 20px; width: 100px;"></select>
11
</div>
12
</body>
13
14
</html>
Advertisement
Answer
Its because you are mapping twice –
JavaScript
1
19
19
1
$(document).ready(function() {
2
let $country;
3
4
$.getJSON("https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json", function(selectData) {
5
function updateSelects() {
6
let cities = selectData[this.value].map((key, val) => {
7
return $("<option />").text(key).val(val);
8
});
9
$("#city").empty().append(cities);
10
}
11
let state;
12
console.log(selectData);
13
$country = $("#country").on("change", updateSelects);
14
for (state in selectData) {
15
$("<option />").text(state).appendTo($country);
16
}
17
$country.change();
18
});
19
});
JavaScript
1
14
14
1
<html>
2
3
<head>
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
5
</head>
6
7
<body>
8
<div style="margin: 50px auto; text-align: center;">
9
<select id="country" style="font-size: 20px; width: 100px;"></select>
10
<select id="city" style="font-size: 20px; width: 100px;"></select>
11
</div>
12
</body>
13
14
</html>