Home > Blockchain >  in my case how I can replace an API returned object value?
in my case how I can replace an API returned object value?

Time:07-21

in the code below, when the "countryName" comes back as "united States", I need to replace to "USA" for the next API call as a parameter to use, because the next API dosen't accept "united States" as country name.

//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);
  }
};

I try to add code like this, but no matter where I put it, it has no effect. how can I achieve this?

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

CodePudding user response:

replace() returns a new string, it doesn't modify the string in place.

But you don't need this, just assign the property to replace it.

And in the condition you have to use == to compare, not =.

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

You don't need the else statement, it doesn't do anything.

  • Related