javascript - 如何将对象分配给数组中的正确对象? react native

标签 javascript react-native

我从服务器获取这个数组:

[{
  "res_id": 0,
  "res_name": "string",
  "res_desc": "string",
  "res_address": "string"
},
etc
]

我必须在 map 上显示标记列表,所以我将我的餐厅映射到标记中以填充坐标,第一个问题是我从服务器获取的数据,它是一个地址,所以我调用:

restos.forEach(x => FetchGeocoder(x.res_address));

然后使用地理编码器获取:

const FetchGeocoder = async (address) => {
        const response = await fetch('https://maps.googleapis.com/maps/api/geocode/json?address=' +
            address + ',' +
            'CABA&key=' + "KEY")
        const responseData = await response.json();
        const markers = responseData.results[0].geometry.location;
        restos.forEach(x => {
            x.res_coords = {
                latitude: markers.lat,
                longitude: markers.lng
            }
        });
    };

我无法解决的问题是我得到了 3 个坐标对象,因为我的数组中有 3 个恢复对象,但只有 1 个坐标对象分配给了我所有的恢复对象,而不是每个坐标都分配给了正确的恢复对象。

在此先感谢您的帮助或帮助!

最佳答案

一个选择是使用 async/awaitrestos 数组的每次迭代期间执行异步函数调用(即 fetchGeocode())。

例如,您可以调整代码以使用以下(或类似)模式:

/* Define async fetchGeocode() function that returns lat/lng data */
const fetchGeocode = async (address) => {
  const res = await fetch('https://maps.googleapis.com/maps/api/geocode/json' + 
                          '?address=' + address + ',CABA&key=' + API_KEY);

  const json = await res.json();
  const { lat, lng } = json.results[0].geometry.location;

  return {
    latitude: lat,
    longitude: lng
  };
};

// Async function adds coords to each resto
async function addCoordsToRestos(restos) => {

  // If restos undefined, or not an iterable array type then return
  // an empty array as a default response
  if(!Array.isArray(restos)) {
      return [];
  }

  // Iterate each resto
  for (const resto of restos) {

    // Mutate current resto by adding res_coords. Call fetchGeocode() 
    // with await to wait for async function to complete before next
    // iteration
    resto.res_coords = await fetchGeocode(resto.res_address);
  }

  // Return mutated restos array to next handler
  return restos
}

用法看起来像这样:

// If called inside an async function
await addCoordsToRestos( restos );

或者:

// If called as a promise
addCoordsToRestos( restos ).then(() => { console.log('done') });

关于javascript - 如何将对象分配给数组中的正确对象? react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262105/

相关文章:

javascript - 使用 xml 引用/链接到 javascript 中的对象

javascript - 未在 Android Phonegap 应用程序中获取 cookie

javascript - 每个选项卡的 AngularJS 唯一选项卡数据

javascript - HTML 电子邮件消息显示为 "HtmlOutput"

android - React Native 中是否可以自定义 Picker 的宽度?

Javascript - `$("a[href* ='video' ]")` 的含义

android - 无法在 app/build.gradle 中在线导入 com.android.build.OutputFile 时解析符号 'build'

reactjs - 由于 track-player 和 react-native-video 中的 exo 播放器版本冲突,react-native-track-player 崩溃

javascript - 根据ID显示具体数据

typescript - 根据世博会上的用户选择更改语言