Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
How to merge variable names into a new variable name

I trying to work with objects and arrays for localization purposes. Now the issue is, that it requires a lot of coding to load the correct value from the objects 1-by-1.

As such, I tried to simplify the process by creating variable names out of other variables. Therefore I check for the lang-attribute and try to get that value as part of another variable name.

However, this does not work at all.

As example I could have an object var text = { en: 'text', de: 'text' }
I could make load the correct text by using:

var language = document.documentElement.lang.toLowerCase();

switch (language) {
  case 'en':
    element.innerHTML = text.en;
    break;
  case 'de'
    element.innerHTML = text.de;
    break;
}

This will be really annoying to code so I tried to use following methodes instead:

element.innerHTML = text.language;
element.innerHTML = `text.${language}`;
...

None of this works of course.

So I'm really in need of help to find a way to create a variable name by merging different variable names such as:

var a = 'text.';
var b = 'en';
var c = a.b; => text.en;

In the end, it must be recognized as a variable name and not as a string!

var text = {
  en: 'Hello World',
  de: 'Hallo Welt',
  es: 'Hola Mundo',
  it: 'Ciao Mundo',
  fr: 'Bonjour Le Monde'
}

/* getting the language of the document */
var language = document.documentElement.lang.toLowerCase();

window.addEventListener('DOMContentLoaded', function() {
  var ele = document.body;
  /*does obviosly not work*/
  var content = `text.${language}`;
  ele.innerHTML = content;
  /*does work*/
  console.log(`the set language is: ${language}`);
});
<!DOCTYPE html>
<html lang="de" dir="ltr">
  <head></head>
  <body></body>
</html>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

const content = text[language]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda