-1

if I have an input and the user have to choose a country from a list, and I have an array of object

[
    {
    "id":1,
    "country": "Afghanistan",
    "cities": [
    "Herat",
    "Kabul",
    "Kandahar",
    "Molah"
    ]
    },
    {
    "id":2,
    "country": "Albania",
    "cities": [
    "Elbasan",
    "Petran",
    "Pogradec"
    ]
    },
    {
    "id":3,
    "country": "Algeria",
    "cities": [
    "Algiers",
    "Annaba",
    "Azazga",
    "Batna City"
    ]
    }]

how can I reach to cities of the the specific country that user choose?

Nora
  • 77
  • 6
  • Did you try writing some code or doing any research, like searching for ["how to find an element in an array of objects"](https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript)? How about `arr.find(e => e.country === userPick).cities`? – ggorlen Oct 01 '22 at 17:52

1 Answers1

0

If you have tags in HTML with values of "id"s in this JSON data. Then whenever the user clicks on each of the countries, you will have the id of that country in your JS with something like this:

var country_id = document.getElementById("IdOfSelectTag").value

Then, you can just filter the cities that are part of that ID by using (if you named the JSON data as "countries_data"):

countries_data.find(e => e.coutry === country_id)

You can then put "countries_data" into a table, select, etc. tags in HTML to show it to users.