[英]Querying Airport Lat and long from Airports.JSON react native
Im trying to query from a JSON file I import like this.我试图从我这样导入的 JSON 文件中查询。 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.我将它放入一个变量中,并从第一个 object 中得到 lat 非常好。
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我有很多对象可以从中获取经纬度,所以我尝试了一个 for 循环
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.我得到未定义的 console.log(airportLat) 帮助将不胜感激。
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.您只有一个
airportLat
值,因此当您遍历机场数据并每次设置airportLat
时,只有最后一次迭代的 object 可以设置airportLat
值。 If airportLat
is still undefined after hitting the for-loop then I suspect the array length is actually 0, ie you are processing an empty array.如果在执行 for 循环后
airportLat
仍然未定义,那么我怀疑数组长度实际上是 0,即您正在处理一个空数组。
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.如果您只是想创建一个机场纬度/经度值的数组,那么我建议将数组值映射到具有
lat
和lon
属性的对象。 If airportData
is actually an empty object then the resultant array will also still be empty.如果
airportData
实际上是一个空的 object,那么结果数组也仍然是空的。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.