Structuring JavaScript object for easy state-city lookup

Hey folks I’m working on a project where I need to organize states and their cities. Right now I have this setup:

let locations = [
  {
    region: 'California',
    towns: ['Los Angeles', 'San Francisco', 'San Diego']
  },
  {
    region: 'New York',
    towns: ['New York City', 'Buffalo', 'Albany']
  }
];

I can access stuff like locations[0].towns[0] but it’s not ideal. What I really want is to find cities when I know the state name. Like if I have ‘California’ I want to get its cities easily.

Also I need to use this for two dropdown menus. The first one should list states and when a state is picked the second one should show its cities. I’ll be loading this data when the page starts.

Any ideas on how to change my locations structure to make this work better? Thanks!

For your state-city lookup scenario, I’d recommend using an object literal with state names as keys and city arrays as values. This structure provides quick, direct access to cities by state name:

const locations = {
  California: ['Los Angeles', 'San Francisco', 'San Diego'],
  'New York': ['New York City', 'Buffalo', 'Albany']
};

This approach allows for efficient lookups (locations[‘California’]) and easy population of dropdowns. For the state dropdown, use Object.keys(locations). When a state is selected, populate the city dropdown with locations[selectedState].

This structure is both performant and intuitive, making it ideal for your specific use case of dropdown population and state-based city retrieval.

I’ve tackled a similar challenge in one of my projects. Instead of an array, I found using an object with state names as keys worked much better. Here’s how I structured it:

let locations = {
  California: ['Los Angeles', 'San Francisco', 'San Diego'],
  'New York': ['New York City', 'Buffalo', 'Albany']
};

This way, you can easily access cities by state name: locations['California']. It’s also perfect for populating dropdowns. For the state dropdown, use Object.keys(locations). When a state is selected, just use locations[selectedState] to populate the city dropdown.

One caveat: if your state names have spaces, use quotes as I did for ‘New York’. This approach significantly simplified my code and improved performance, especially when dealing with larger datasets. Hope this helps!

hey, i actually did something similar for a client recently. instead of ur current setup, try using a Map object. it’s super handy for key-value pairs like states and cities. here’s a quick example:

let locations = new Map([
  ['California', ['Los Angeles', 'San Francisco', 'San Diego']],
  ['New York', ['New York City', 'Buffalo', 'Albany']]
]);

u can easily get cities with locations.get(‘California’). works great for dropdowns too!