Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!