0

new to Javascript and have a basic question.

Say I have the following array of arrays:

const cities = [
  {
    "id": 4048332,
    "name": "Aurora",
    "state": "IN",
    "country": "US",
    "coord": {
      "lon": -84.901337,
      "lat": 39.056999
    }
  },
  {
    "id": 4048388,
    "name": "New Pekin",
    "state": "IN",
    "country": "US",
    "coord": {
      "lon": -86.016922,
      "lat": 38.505058
    }
  },
  {
    "id": 4254010,
    "name": "Austin",
    "state": "IN",
    "country": "US",
    "coord": {
      "lon": -85.808029,
      "lat": 38.758389

    }
}

Say I have a variable that is a user input of a city, and if the city matches one of the cities listed in the array return the city ID relative to that array. So if a user inputs "New Pekin", how would I go about getting a return of 4048388? Thank you

CRice
  • 29,968
  • 4
  • 57
  • 70
SatoriBlue
  • 93
  • 4
  • 2
    What have you tried? [This might be a good place to start.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – CRice May 04 '20 at 23:12
  • 1
    That's an array of **objects**, not an array of arrays. – Pointy May 04 '20 at 23:13
  • 2
    You could use something like this: ```javascript function(searchKey) { let keysToSearch = ['name'] return cities.filter(city => { return keysToSearch.some(key => { if (city[key]) { return city[key].includes(searchKey) } return false }) }) } ``` This will return a list of cities where one of the properties you specify in the `keysToSearch` include the `searchKey`. – Souf May 04 '20 at 23:20
  • @Souf may as well post that as the answer. – Zze May 04 '20 at 23:29
  • I couldn't because the post is closed :/ – Souf May 05 '20 at 14:09

0 Answers0