Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I access random key value pairs with JS?

Im creating an app that randomly generates information for a person. One being, the state, city, zip, and area codes that they reside in. Obviously I cannot randomly generate a city, without accessing that cities state. i.e. "Miami, New York". How can I efficiently write this code with nested data that I can access randomly? So if ‘omaha’ is chosen at random it should also access those value pairs with it.

let cities = {
  omaha: {
    city: "Omaha",
    state: "Nebraska",
    zip: ["68102", "68116", "68198"],
    areaCode: ["302", "402"],
  },

  saltLake: {
    city: "Salt Lake City",
    state: "Utah",
    zip: ["84095", "84065", "84121"],
    areaCode: ["385", "801"],
  },
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so lets say, omaha city is chosen randomly in the code, then you can either save it a variable like :

let cityChoosen = 'omaha'

or you can use the ‘omaha’ city name directly.

you can city’s key value pairs like this

if you are saving the city name in variable then:

cities[cityChoosen].city // Output : 'Omaha'
cities[cityChoosen].state //Output :'Nebraska'
cities[cityChoosen].areaCode //Output :["302", "402"]

and if you want to use ‘omaha’ city directly as a string, then you can use it like below :

cities['omaha'].city // Output : 'Omaha'
cities['omaha'].state //Output :'Nebraska'
cities['omaha'].areaCode //Output :["302", "402"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading