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

237
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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