Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda