简体   繁体   中英

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. ie "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"],
  },
};

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"]

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)
      ]
    );

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