I have an error here at graphql. I'm trying get an airport name through JSON data. I need a single item which's (name of the airport) but I'm receiving array of items with it's city, country, geolocation and so on. Here's the code I'm trying with...
const getNameOfAirport = (name:any)=>{
return AIRPORTS.filter((i)=>{
if(i.iata_code === name){
return i.name.length;
}
})
}
when i run condole.log(getNameOfAirport("BLR")) i'm receiving
[
{
name: 'Bangalore',
city: 'Bangalore',
country: 'India',
iata_code: 'BLR',
_geoloc: { lat: 12.949986, lng: 77.668206 },
links_count: 195,
objectID: '3131'
}
]
I need a response with
Bangalore
Any answers much appreciated. Let me know where i'm doing wrong.
Note: I'm using typescript. It works with JSX as i expected. It's going wrong with TS
Here are multiple mistakes
Well you use Typescript, but put
any
for your type. Why do you even use typescript at the first place? But thats a other question Here:I see you use
AIRPORTS
, and its an array. But you dont pass it into the function, so the array is outside the function. Sideeffects are bad. You should avoid that.Array.filter()
is the wrong method i guess. You should probably try.find()
You should also create an interface. Try this:
Then you call it with:
A side note: The name
getNameOfAirport
is kinda bad naming. I would suggest to use something likegetAirportNameByIataCode
. By reading the function its pretty clear whats doing.