![](/img/trans.png)
[英]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.