You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API返回对象countryName值替换问题:JavaScript代码实现求助

问题解决:替换geonames API返回的国家名称

你的代码存在三个关键问题,导致替换逻辑无效:

  1. 条件判断误用了赋值运算符=,而非比较运算符===
  2. replace方法返回新字符串,不会修改原变量,需要重新赋值
  3. 未处理大小写匹配问题(比如API可能返回"United States"而非全小写)

以下是两种正确的实现方式:

方式一:构建对象时直接处理

//geonames API call
const getGeo = async city => {
  try {
    const geoAllData = await axios.get(`${geoBaseURL}=${encodeURIComponent(city)}&maxRows=1&username=${process.env.geoUsername}`);
    const rawCountry = geoAllData.data.geonames[0].countryName;
    // 统一转小写判断,避免大小写差异问题
    const countryName = rawCountry.toLowerCase() === "united states" ? "USA" : rawCountry;
    
    const geoData = {
      lat: geoAllData.data.geonames[0].lat,
      lng: geoAllData.data.geonames[0].lng,
      countryName: countryName
    };  
    console.log(geoData);
    return geoData;
  } catch (error) {
    console.log("geo API error", error);
  }
};

方式二:构建对象后修改

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

    // 修正判断逻辑并重新赋值
    if (geoData.countryName.toLowerCase() === "united states") {
      geoData.countryName = "USA";
    }

    console.log(geoData);
    return geoData;
  } catch (error) {
    console.log("geo API error", error);
  }
};

额外优化说明

  • 将await axios.get移入try块,确保请求失败时能进入catch捕获错误
  • 用toLowerCase()统一转换为小写后比较,兼容API返回的不同大小写格式(如"United States"、"UNITED STATES"等)

内容的提问来源于stack exchange,提问作者Qin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 12:21:28