用另一个字典中的值替换字典中的值

时间:2020-01-18 09:24:58

标签: javascript node.js

我有一本英语词典,我正在尝试使用translationTerms替换英语词典中的值以使其成为西班牙语词典。有人可以指导我做这个吗?

var englishDict = {
  "name": "Please enter your name",
  "list": ["translate", "object", "made"],
  "nested": {
    "hello": "hello",
    "world": "world"
    }
};


var translatedTerms = {
  "Please enter your name" : "Por favor, escriba su nombre",
  "translate" : "traducir",
  "object" :"objeto",
  "made" : "hecho",
  "hello" : "hola",
  "world": "mundo"
}

我想要的输出

var spanishDict = {
      "name": "Por favor, escriba su nombre",
      "list": ["traducir", "objeto", "hecho"],
      "nested": {
        "hello": "hola",
        "world": "mundo"
        }
    };

3 个答案:

答案 0 :(得分:2)

var englishDict = {
    "name": "Please enter your name",
    "list": ["translate", "object", "made"],
    "nested": {
        "hello": "hello",
        "world": "world"
    }
};


var translatedTerms = {
    "Please enter your name" : "Por favor, escriba su nombre",
    "translate" : "traducir",
    "object" :"objeto",
    "made" : "hecho",
    "hello" : "hola",
    "world": "mundo"
}

var spanishDict = {}

var key,value,newObject;
for(key in englishDict){
    value = englishDict[key];
    if(typeof value ==='string'){ // If it's a string
        if(value in translatedTerms)
            spanishDict[key] = translatedTerms[value]; // Replace from translatedTerms
        else
            spanishDict[key] = value; // If not found in translatedTerms, keep original
    }
    else if(Array.isArray(value)){ // If it's an array
        spanishDict[key] = value.map((item)=>{
            if(item in translatedTerms) // Replace from translatedTerms
                return translatedTerms[item];
            return item; // If not found in translatedTerms, keep original
        })
    }
    else if(typeof value === 'object' && value !== null){ // If it's an object and not null
        newObject = {};
        Object.keys(value).map((_key)=>{
            if(_key in translatedTerms)
                newObject[_key] = translatedTerms[_key]; // Replace from translatedTerms
            else
                newObject[_key] = value[_key]; // If not found in translatedTerms, keep original
        })
        spanishDict[key] = newObject;
    }
}
console.log(spanishDict)

输出

{ name: 'Por favor, escriba su nombre',
  list: [ 'traducir', 'objeto', 'hecho' ],
  nested: { hello: 'hola', world: 'mundo' } }

答案 1 :(得分:1)

translate()函数以递归方式迭代字典,并且如果当前的dict是:

  1. 一个数组-映射该数组,并在每个项目上调用translate()
  2. 对象-将对象转换为条目,映射条目,并对每个条目的值调用translate()。然后使用Object.fromEntries()将条目转换回对象。
  3. other-从terms对象返回该项目的值,或者如果terms对象上不存在该项目本身,则返回该项目本身。

您需要处理以下四种情况:

  1. dict是一个数组

const translate = (dict, terms) => {
  if(Array.isArray(dict)) { // if it's an array map it
    return dict.map(t => translate(t, terms));
  }
  
  if(typeof dict === 'object' && dict !== null) {
    return Object.fromEntries( // if it's an object map the entries, and convert them back to object
      Object.entries(dict)
        .map(([k, v]) => [k, translate(v, terms)]
      )
    );
  }
  
  return dict in terms ? terms[dict] : dict; // translate if exists as a key on terms, and return if not
};

const englishDict = {"name":"Please enter your name","list":["translate","object","made"],"nested":{"hello":"hello","world":"world"}};

const translatedTerms = {"Please enter your name":"Por favor, escriba su nombre","translate":"traducir","object":"objeto","made":"hecho","hello":"hola","world":"mundo"};

const result = translate(englishDict, translatedTerms);

console.log(result);

答案 2 :(得分:0)

现代(ECMAScript 2019),纯净,不可更改的功能解决方案:

const englishDict = {
  "name": "Please enter your name",
  "list": ["translate", "object", "made"],
  "nested": {
    "hello": "hello",
    "world": "world"
    }
}

const translatedTerms = {
  "Please enter your name" : "Por favor, escriba su nombre",
  "translate" : "traducir",
  "object" :"objeto",
  "made" : "hecho",
  "hello" : "hola",
  "world": "mundo"
}

const translateObject = obj => {
  const translatedEntries = Object
     .entries(obj)
     .map(([key, value]) => ([key, translate(value)]))

  return Object.fromEntries(translatedEntries)
}

const translate = el => {
  if (typeof el === 'string') {
    return translatedTerms[el]
  }

  if (Array.isArray(el)) {
    return el.map(word => translatedTerms[word])
  }

  if (typeof el === 'object' && el !== null) {
    return translateObject(el)
  }

  return el
}
// solution:
translateObject(englishDict)
相关问题