[英]How to pull values from JSON string into list items using JavaScript
[英]How to pull a list of values from a JSON string and iterate through them?
我有一个国家到国家的动态 JSON map。 前任。 {"Canada":["Ontario","Quebec","Alberta"],"USA":["Michigan","Maine","New Hampshire"]}
我知道所选的国家名称。
问题:如何从 map 中获取所选国家名称的州列表并遍历这些值?
<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>
也许将它们组成一个数组,然后就像其他数组一样。
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]));
示例中的更多操作:
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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.