简体   繁体   中英

How to pull a list of values from a JSON string and iterate through them?

I have a dynamic JSON map of countries to states. ex. {"Canada":["Ontario","Quebec","Alberta"],"USA":["Michigan","Maine","New Hampshire"]}

I know the selected country name.

QUESTION: How do I get the list of states for the selected country name out of the map and iterate through the values?

<script>
function onChangeCountry() {
    var selectedCountry = $('#country').find(":selected").text();
    alert("010 selectedCountry = "+ selectedCountry); // <<-- this gets me the selected country, works fine

    var jsonMapCountryToStates = ${jsonMapCountryToStates};
    alert("020 JSON.stringify(jsonMapCountryToStates) = "+JSON.stringify(jsonMapCountryToStates)); // <-- this shows me the whole map

    // how do I iterate through the list of states for 'selectedCountry' ?
}
</script>

make an array of them perhaps, then it is like every other array.

 let fundata = {"Canada":["Ontario","Quebec","Alberta"],"USA":["Michigan","Maine","New Hampshire"]}; console.log(Array.from(fundata.USA)); // or using the other syntax: let namedPlace = "USA"; console.log(Array.from(fundata[namedPlace]));

A little more action in an example:

 var fundata = { "Canada": ["Ontario", "Quebec", "Alberta"], "USA": ["Michigan", "Maine", "New Hampshire"] }; function onChangeCountry(e) { let selectedCountry = $(this).find(":selected").val(); console.log("010 selectedCountry = " + selectedCountry); fundata[selectedCountry].forEach(element => console.log("State:", element)); } for (const prop in fundata) { $('#country').append("<option value='" + `${prop}` + "'>" + `${prop}` + "</option>") console.log(`${prop}: ${fundata[prop]}`); } $("#country").on("change", onChangeCountry);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="country" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM