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

235
Views
Node JS - Loop throught JSON and map values

I have a JSON like this:

{
  "generic": {
    "tables": {
      "header": "Header",
      "columns": "Columns"
    },
    "yes": "Yes",
    "no": "No"
  }
}

But with thousands of lines and more nested objects. I need to translate all this strings, so I'm making a script to do it. How can I loop through each string and replace it with something?

I've searched and found this thread: Looping through JSON with node.js but I can't find any solution that fits my needs.

I made this quick script:

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('en.json', 'utf-8'));

const translate = (obj, path = '') => {
  const keys = Object.keys(obj);

  keys.forEach((key) => {
    const type = typeof obj[key];

    if (type === 'object') {
      translate(obj[key], path === '' ? key : path + '.' + key);
    } else {
      console.log(path + ' --> [' + key + ']: ' + obj[key]);
    }
  });
};

translate(obj);

It loops through the array. In the console log line I have the full path of the translation item (i.e.: 'generic.tables.header') and I have the key and value of the translation.

How can i make a new object containing the keys ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think I found a way, instead of saving the path, create an empty object and insert the keys there:

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('en.json', 'utf-8'));

const newObj = {};

const translate = (obj, path = '', objVal) => {
  const keys = Object.keys(obj);

  keys.forEach((key) => {
    const type = typeof obj[key];

    if (type === 'object') {
      objVal[key] = {};
      const newObjVal = objVal[key];

      translate(obj[key], path === '' ? key : path + '.' + key, newObjVal);
    } else {
      objVal[key] = obj[key];
      //console.log(path + ' --> [' + key + ']: ' + obj[key]);
    }
  });
};

translate(obj, '', newObj);
about 4 years ago · Juan Pablo Isaza Report
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!