Razmi
Razmi

Reputation: 209

Getting the values from a JSON

each entry in the JSON, looks like this:

{
  "ALBA": [
    {
      "name": "ABRUD",
      "zip": "515100",
      "lat": "46.274675",
      "long": "23.065029"
    },
    {
      "name": "ABRUD-SAT",
      "zip": "515101",
      "lat": "46.283967",
      "long": "23.061093"
    },
}

The first object is the county name, I have more of them, but I just gave an example, the nested objects are the cities. What I want is a way to display them in a select tag in HTML, but I can't manage to do it.

I have the following code, until now:

const getCities = () => {
    // Object.keys(regions).map(function(key, index) {
    //   console.log(regions[key]);
    // })
    for (const region in regions) {
      console.log(region); //this returns exactly what i want
    //cities.push(region)
    }
  }
  getCities();

And in html:

<div>
            <select name="city">
              <option value={cities}>{cities}</option>
            </select>
</div>

How can I make this select tag return me exactly the counties and how to make another one to show me the cities name based on the selected county?

EDIT: I managed to do it doing the following:

const getCities = () => {
    for (const region in regions) {
      cities.push(region);
    }
    return cities
  }
  getCities();


<div>
        <label htmlFor="city">County</label>
        <select name="city"
        onChange={(e) => setCity(e.target.value)}
        >
          {cities.map((city) => {
            return (
              <option value={city} key={city}>{city}</option>
            )
          })}
        </select>
      </div>

Upvotes: 0

Views: 72

Answers (1)

Nalin Ranjan
Nalin Ranjan

Reputation: 1782

Try following....

const countryCityMap = {
  "ALBA": [{
      "name": "ABRUD",
      "zip": "515100",
      "lat": "46.274675",
      "long": "23.065029"
    },
    {
      "name": "ABRUD-SAT",
      "zip": "515101",
      "lat": "46.283967",
      "long": "23.061093"
    }
  ]
}

function bindCountryCity(countryCityMap) {
  const countrySelector = document.querySelector('#countrySelector');

  const citySelector = document.querySelector('#citySelector');

  if (countrySelector) {
    clearOptions(countrySelector);
    addDefault(countrySelector);

    // Populate Countries
    Object.keys(countryCityMap).forEach(country => addOption(countrySelector, country, country));

    countrySelector.onchange = countrySelected
  }

  if (citySelector) {
    citySelector.onchange = function(selector) {
      console.log('[City Selection Changed]', selector.target.value);
    }
  }

  function addDefault(selector) {

    if (selector) {
      const defaultValue = selector.getAttribute('data-default-value') || 'select';
      const defaultText = selector.getAttribute('data-default-text') || 'select';
      addOption(selector, defaultText, defaultValue);
    }
  }


  function addOption(selector, optionText, optionValue) {
    if (selector) {
      selector.add(new Option(optionText, optionValue));
    }
  }


  function clearOptions(selector) {

    if (selector) {
      while (selector.options.length) {
        selector.remove(0);
      }
    }
  }

  function countrySelected(selectionChanged) {
    const selectedCountry = selectionChanged.target.value;
    console.log('[Country Selection Changed]', selectedCountry);

    clearOptions(citySelector);
    addDefault(citySelector);
    if (countryCityMap[selectedCountry]) {
      // populate corresponding cities
      countryCityMap[selectedCountry].map(cityEntry => getCityNames(cityEntry)).filter(x => (x || '').trim()).forEach(city => addOption(citySelector, city, city));
    }

    function getCityNames(cityEntry) {
      if (cityEntry && (cityEntry.name || '').trim()) {
        return (cityEntry.name || '').trim();
      }
    }
  }
}

bindCountryCity(countryCityMap);
<div>
  <select id="countrySelector" data-default-value="select_a_country" data-default-text="Select a country" style="margin: 10px; float: left">
    <option value="select_a_country">Select a country</option>
  </select>
</div>

<div>
  <select id="citySelector" data-default-value="select_a_city" data-default-text="Select a city" style="margin: 10px">
    <option value="select_a_city">Select a city</option>
  </select>
</div>

Upvotes: 1

Related Questions