【问题标题】:How to pull a list of values from a JSON string and iterate through them?如何从 JSON 字符串中提取值列表并遍历它们?
【发布时间】:2020-04-28 04:18:32
【问题描述】:

我有一个国家到州的动态 JSON 地图。前任。 {"Canada":["Ontario","Quebec","Alberta"],"USA":["Michigan","Maine","New Hampshire"]}

我知道所选的国家/地区名称。

问题:如何从地图中获取所选国家名称的州列表并遍历值?

<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>

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    也许将它们组成一个数组,然后就像其他数组一样。

    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" />

    【讨论】:

    • 也可以使用const states = [...fundata[namePlaced]
    • 谢谢!工作。最后它看起来像这样:var arrStates = Array.from(jsonMapCountryToStates[selectedCountry]); for (var i = 0; i &lt; arrStates.length; i++) { var state = arrTableNames[I]; alert("state = "+state); }
    猜你喜欢
    • 2014-04-20
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2021-06-30
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多