Home > Software engineering >  Map array of locales and change each locale to language name
Map array of locales and change each locale to language name

Time:05-11

Using Next.js, I'm getting the current locale and all available locales for a language selection menu:

const {cl, al} = useContext(LangContext);
// cl = "en-US"
// al = ["en-US", "de-DE"]

I wrote this function to return the full language name:

const clAlias = ()=> {
    if (cl === "en-US") { return "English" };
    if (cl === "de-DE") { return "Deutsch" };
}

Now I want to map al , but instead of having ["en-US", "de-DE"] I want to have ["English", "Deutsch"]. It not only looks better but also makes it easier for the user to select their language. What would be the best way to do so?

CodePudding user response:

How about an object.

const clAlias = {
  "en-US": "English",
  "de-DE": "Deutsch"
}
//...
al.map(x => clAlias[x])

CodePudding user response:

You can use Array.from method. It return new array without change al

And don't forget add arguments in clAlias() like clAlias(cl)

const al = ["en-US", "de-DE"];
const clAlias = (cl) => {
  if (cl === "en-US") {
    return "English";
  }
  if (cl === "de-DE") {
    return "Deutsch";
  }
};

const answer = Array.from(al, (e) => clAlias(e));
console.log(answer);

  • Related