API返回对象countryName值替换问题:JavaScript代码实现求助
问题解决:替换geonames API返回的国家名称
你的代码存在三个关键问题,导致替换逻辑无效:
- 条件判断误用了赋值运算符
=,而非比较运算符=== replace方法返回新字符串,不会修改原变量,需要重新赋值- 未处理大小写匹配问题(比如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
相关产品推荐
相关产品推荐

