从 Fetch 返回的对象中向键添加了新对象,并且需要重新获取新添加的值

问题描述

我从 API 获取 JSON,一旦获取该数据,我将使用另一个 API 获取地理编码值并将其添加到对象中。

这是获取后的初始对象:

{ approved: 1
 body: "sample comments being made. "
 categories: (4) [{…},{…},{…}]
 created_at: "2020-12-18T19:38:43.000000Z"
 email: "[email protected]"
 geocode: null
 id: 7
 image_id: "7"
 is_moderated: 1
 updated_at: "2020-12-21T20:57:04.000000Z"
 zip: "60611"
}

然后我使用这个循环来使用每个对象的 zip 来获取地理编码信息并将其添加到每个对象中。

for (const property in data) {
  getLocation@R_734_4045@ion(data[property]);
  const allApprovedComments = createCommentElement(data[property]);
  commentContentParent.append(allApprovedComments);
}

这就是 getLocation@R_734_4045@ion 函数的样子:

  function getLocation@R_734_4045@ion(comment) {
    const fullPath = geoCode + '?address=' + comment.zip + '&key=' + geocodeApi;

    fetch(fullPath)
      .then(function fetchResponse(response) {
        return response.json();
      })
      .then(function parseData(data) {
        comment.geocode = {
          county: data.results[0].address_components[2].long_name,state: data.results[0].address_components[3].long_name,stateAbbrv: data.results[0].address_components[3].short_name,lat: data.results[0].geometry.location.lat,lng: data.results[0].geometry.location.lng,};
      })
      .catch(function fetchError(error) {
        return error;
      });
  }

那么这就是返回的对象:

{ approved: 1
  body: "sample comments being made. "
  categories: [{…}]
  created_at: "2020-12-18T19:38:43.000000Z"
  email: "[email protected]"
  geocode: {
    county: "Cook County",state: "Illinois",stateAbbrv: "IL",lat: 41.8925085,lng: -87.61616959999999
  },id: 7
  image_id: "7"
  is_moderated: 1
  updated_at: "2020-12-21T20:57:04.000000Z"
  zip: "60611"
}

虽然,我可以访问 body 键和所有其他键,即使 console.log(object) 显示 geocode 键在我尝试访问键时具有值,例如:{{ 1}} 返回的值始终为 object.geocode。我不明白为什么会发生这种情况,对于解决此问题的任何帮助表示感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)