簡體   English   中英

用另一個字典中的值替換字典中的值

[英]Replace values in a dictionary with values from another dictionary

我有一本英語詞典,我正在嘗試使用翻譯的術語替換英語詞典中的值,使其成為西班牙語詞典。 有人可以指導我完成這個嗎?

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"
        }
    };
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' } }

這個translate()函數遞歸地迭代字典,如果當前的dict是:

  1. 數組 - 映射數組,並在每個項目上調用translate()
  2. 對象 - 將對象轉換為條目,映射條目,並對每個條目的值調用translate() 然后使用Object.fromEntries()將條目轉換回對象。
  3. 其他-返回從項目的價值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);

現代(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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM