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"],
},
};
CodePudding user response:
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"]
CodePudding user response:
Final Result, for anyone interested. Thanks again for all the help!
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"],
},
};
let randomCity = Object.keys(cities);
let chosenCity = randomCity[Math.floor(Math.random() * randomCity.length)];
console.log(
cities[chosenCity].city,
cities[chosenCity].areaCode[
Math.floor(Math.random() * cities[chosenCity].areaCode.length)
]
);