简体   繁体   中英

Find all cities in a country/state or finding the state/country given a city from JSON data

I have county/state/city data in JSON (shown below). I want to find all cities given a state/country and given a city, need to find the state and country.

List all cities in country: usa
List all cities in states: Alabama
List the state and country for city: Adamsville

{
  "country": "usa",
  "states": [
    {
      "name": "Alabama",
      "state_code": "AL",
      "cities": [
        {
          "name": "Abbeville",
          "latitude": "31.57184000",
          "longitude": "-85.25049000"
        },
        {
          "name": "Adamsville",
          "latitude": "33.60094000",
          "longitude": "-86.95611000"
        }
      ]
    },
    {
      "name": "Alaska",
      "state_code": "AK",
      "cities": [
        {
          "name": "Akutan",
          "latitude": "54.13350000",
          "longitude": "-165.77686000"
        },
        {
          "name": "Aleutians East Borough",
          "latitude": "54.85000000",
          "longitude": "-163.41667000"
        }
      ]
    }
  ]
}

Here are built-in Array functions that will help you get what you want.

Array.prototype.find() - returns the value of the first element in an array that satisfies the provided test.

To find the state object in your JSON data , you can do this:

const findState = (name) => data.states.find(state => state.name === name);

let alaska = findState('Alaska');
// { "name"; "Alaska", "state_code": "AK", "cities": [...] }

To find the cities in a state, use the above findState to get the state object, then Array.prototype.map() will form an array of just the city names:

let alaska = findState('Alaska');
let citiesInAlaska = alaska.cities.map(city => city.name);
// [ "Akutan", "Aleutians East Borough" ]

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