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:
const getNameOfAirport = (name:any)=>{
return AIRPORTS.filter((i)=>{
if(i.iata_code === name){
return i.name.length;
}
})
}
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:
const getNameOfAirport = (
airports: Airport[],
name: string
): string | undefined => {
return airports.find((airport) => airport.iata_code === name)?.name;
};
interface Airport {
name: string;
city: string;
country: string;
iata_code: string;
_geoloc: {
lat: number;
lng: number;
};
links_count: number;
objectID: string;
}
Then you call it with:
getNameOfAirport(AIRPORTS, "BLR")
A side note: The name getNameOfAirport
is kinda bad naming. I would suggest to use something like getAirportNameByIataCode
. By reading the function its pretty clear whats doing.