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

91
Visualizações
Combining part of an object's name with a variable with JavaScript

Alright, I need some assistance from the js experts out there. Here's my problem: I receive an object from a CMS which contains two strings inside:

{pageContent.title}

Inside the object I get:

"title":{
"_type":"localeString"
"en":"Privacy Policy"
"es":"Política de Privacidad"
}

Each string represents a locale, and the page needs to render the correct one depending on the current locale. For that I'm using a simple router hook:

const router = useRouter()
const locale = router.locale

So now locale returns either en or es

To render the object on the page I'd do: {pageContent.title.es} for spanish and {pageContent.title.en} for English, and so on.

However, I need the .es and .en part to be dynamic, and pick up that value from locale since now there are only two languages, but more will be added in the future.

I found a very hacky solution that works but I'd prefer something more elegant.

First, I join both, but using the object partial name as a string. Then I remove the '' (unstringing it)

let localeTitle = 'pageContent.title.' + locale
localeTitle = localeTitle.replace(/"/g, '')

Then on the page, I eval() that new string: {eval(localeTitle)}

Now, I know this isn't the correct or best way of doing this.

And, before you ask why I'm not getting the corresponding language directly on the query, I tried. I'm using getStaticProps to fetch the data, which doesn't allow hooks to be used so I can't access the locale from the router.

Any ideas?

about 4 years ago · Juan Pablo Isaza
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