Skip to content

Querying Airport Lat and long from Airports.JSON react native

Im trying to query from a JSON file I import like this. you can find the File here

import * as airportData from '../../Data/airports.json'; 

I put it into a variable and get the lat from the first object perfectly fine.

 let arr = airportData;

 let airportIcao = Object.keys(arr)[0];

 let airportLat = arr[airportIcao]['lat']; 

I have many objects to get the lat and long from so I tried a for loop

  let arr = airportData;
     let airportLat;

     var i;
     for (i=0; i < arr.length; i++) {
      let airportIcao = Object.keys(arr)[i];
      airportLat = arr[airportIcao]['lat'];

    }

I get Undefined for my console.log(airportLat) help would be appreciated.

Answer

Issue

You’ve only a single airportLat value, so when you loop over the airport data and set the airportLat each time then only the last iterated object can set the airportLat value. If airportLat is still undefined after hitting the for-loop then I suspect the array length is actually 0, i.e. you are processing an empty array.

Solution

If you are simply trying to create an array of the airport lat/long values then I suggest mapping the array values to objects with lat & lon properties. If airportData is actually an empty object then the resultant array will also still be empty.

Object.values(airportData).map(({ lat, lon }) => ({ lat, lon }))

const getData = async () => {
  const data = await fetch(
    "https://raw.githubusercontent.com/mwgg/Airports/master/airports.json"
  ).then((res) => res.json());
  
  const latLongArray = Object.values(data)
    .slice(-10) // <-- grabbing last 10 for brevity
    .map(({ lat, lon }) => ({ lat, lon }));
    
  console.log(latLongArray);
};

getData();