【问题标题】:Node JS - Loop throught JSON and map valuesNode JS - 循环遍历 JSON 和映射值
【发布时间】:2021-11-22 12:08:42
【问题描述】:

我有一个这样的 JSON:

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

但有数千行和更多嵌套对象。我需要翻译所有这些字符串,所以我正在制作一个脚本来完成它。如何遍历每个字符串并用某些东西替换它?

我已经搜索并找到了这个帖子:Looping through JSON with node.js,但我找不到任何适合我需要的解决方案。

我制作了这个快速脚本:

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);

它循环遍历数组。在控制台日志行中,我有翻译项目的完整路径(即:'generic.tables.header'),并且我有翻译的键和值。

如何创建一个包含键的新对象?

【问题讨论】:

    标签: javascript node.js json


    【解决方案1】:

    我想我找到了一种方法,而不是保存路径,而是创建一个空对象并在那里插入键:

    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);
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 2023-03-15
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多