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

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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