简体   繁体   中英

Loop through multiple Arrays in Json file using JavaScript

Excuse my lack of knowledge as i have never dealt with Json arrays. I'm trying to create a dynamic Dropdown system where i have The Country DropDown and the cities DropDown, and i want to fetch my data from a Json file that has multiple arrays in it, here's an example of the Json file i have:

{"Array1":["A","B","C","D"] , "Array2":["W","X","Y","Z"]}

Please How can i load the file and then loop through these arrays in a way that i can have "Array1" and "Array2" as values in the countries dropdown and then when i select on of the two generate the Cities (What's inside of array1 or arrya2) in the second dropdown.

Any help will be massively appreciated.

 const data = {"Array1":["A","B","C","D"], "Array2":["W","X","Y","Z"]}; Object.keys(data).forEach(arrName => { $(Layer1).append(`<option>${arrName}</option>`); }); $(Layer1).on('change', function() { const arrName = $(this).val(); if (arrName) { $('.dynamic').remove(); data[arrName].forEach(value => { $(Layer2).append(`<option class="dynamic">${value}</option>`); }); $(Layer2).show(); } else { $(Layer2).hide(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="Layer1"> <option disabled selected></option> </select> <select id="Layer2" style="display: none;"> <option disabled selected></option> </select>

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