I want to change how this regions array is organized so I can directly use a province name to get its towns array. What would be the best way to restructure this?
I’m building a dropdown system where picking from the first dropdown should fill the second one. I’ll load this data when the page starts. I need to first loop through by index to show all provinces, then later use the selected province name to find its towns.
Any suggestions on how to modify this structure or convert it to something more suitable?
Keep your original array and make a helper function to convert it when you need the map. Something like function getRegionsMap(regions) { return regions.reduce((map, region) => { map[region.Province] = region.Towns; return map; }, {}); } You get flexibility this way - use the array for displaying provinces with regions.map((region, index) => region.Province), then call the helper once for your second dropdown lookup. I did this same thing on a project where I needed both the iteration order and direct access. Worked great.
Use a Map object instead. You’ll get proper iteration order and direct key access. Set it up like this: const regions = new Map([['Ontario', ['Toronto','Ottawa','Hamilton']], ['Quebec', ['Montreal','Quebec City','Laval']]]). For the first dropdown, use Array.from(regions.keys()) to get provinces in order. For the second, just call regions.get(selectedProvince) to grab the towns. Maps keep insertion order (unlike regular objects) and they’re faster for frequent lookups. I’ve used this for cascading dropdowns in multiple projects - handles edge cases way better than object literals.
Switch to an object with province names as keys - ditch the array. Like var regions = {"Ontario": ['Toronto','Ottawa','Hamilton'], "Quebec": ['Montreal','Quebec City','Laval']}. Then just do regions["Ontario"] to grab the towns. Way cleaner for dropdowns.