【问题标题】:in my case how I can replace an API returned object value?就我而言,如何替换 API 返回的对象值?
【发布时间】:2022-07-21 16:38:16
【问题描述】:

在下面的代码中,当“countryName”返回为“United States”时,我需要将下一个 API 调用替换为“USA”作为要使用的参数,因为下一个 API 不接受“united”国家”作为国家名称。

//geonames API call
const getGeo = async city => {
  const geoAllData = await axios.get(`${geoBaseURL}=${encodeURIComponent(city)}&maxRows=1&username=${process.env.geoUsername}`);
  try {
    const geoData = {
      lat: geoAllData.data.geonames[0].lat,
      lng: geoAllData.data.geonames[0].lng,
      countryName: geoAllData.data.geonames[0].countryName,
      }  
      console.log(geoData)
      return geoData;
  } catch (error) {
    console.log("geo API error", error);
  }
};

我尝试添加这样的代码,但无论我放在哪里,它都没有效果。我怎样才能做到这一点?

 if(geoData.countryName = "united states"){
        geoData.countryName.replace("united states", "USA")
    } else {
      geoData.countryName
    } 

【问题讨论】:

    标签: javascript api


    【解决方案1】:

    replace() 返回一个新字符串,它不会在原地修改字符串。

    但你不需要这个,只需分配属性来替换它。

    在这种情况下,您必须使用== 进行比较,而不是=

    if (geoData.countryName == "united states") {
      geoData.countryName = "USA";
    }

    您不需要else 语句,它没有任何作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多