如何将API数据转换为本地语言数据?

时间:2017-02-22 11:54:41

标签: javascript reactjs internationalization redux flux

我正在研究reactJS + Flux项目。我正在尝试将我的网站转换为多语言。我已经拥有了来自API的所有可能值的字典。我想用我的字典值替换API的实际值。

例如:

来自API的

我得到以下格式数据:

data = {
 basic: {
  name: "ajay kumar",
  country: "India",
  State: "Maharashtra",
  City: "Mumbai"
 }
}

在我的印地文词典中,我已经得到了所有的价值:

data= {
hindi: {
"country" : {
     "India" : "भारत"
 },
state: {
        "Andaman & Nicobar Islands": "अंदमान अँड निकोबार आयलँड्स",
        "Andhra Pradesh": "आंध्र प्रदेश",
        "Arunachal Pradesh": "अरुणाचल प्रदेश",
        "Assam": "आसाम",
        "Bihar": "बिहार",
        "Maharashtra": "महाराष्ट्र"
},
"city" :{
   "Mumbai" : "मुंबई"
}
}
}

我想从给定的字典中更改所有值。

1 个答案:

答案 0 :(得分:0)

首先要确保你的词典不能简单:

{englishWord1: hindiWord1,
 ....
 englishWordn: hindiWordn}

如果不能,我会使用data.basicObject.keys(object)中提取密钥,然后我会定义I函数,将字典中的单词与对象中的单词进行映射(translate(section, word, dictionary) => [section, translatedWord] )。 使用Object.keys(object),您将获得与字典中的部分(CountryState ecc)对应的键数组,然后使用map转换数组中的每个元素以进行di您使用translate(..)并获得翻译单词数组:[[section1:translatedWord1],...[sectionn,translatedWordn]]。然后使用一个带数组的函数并返回一个对象(arrayToObject([])=>{}),你将获得你的翻译对象。

//This is your dictionary
engToHindi = {
  Country : {
    India: 'valueIndia',
  },
  State: {
    Maharashtra: 'valueMaharashtra',
  },
  City :{
   Mumbai: 'valueMumbai',
  }
}

data = {
 basic: {
  Name: "ajay kumar",
  Country: "India",
  State: "Maharashtra",
  City: "Mumbai"
 }
}

function arrayToObject(array){
  object = {}
  array.map(x => {object[x[0]] = x[1]});
  return object;
}


function translate(section, word, dictionary){
  // If the section doesn't exist do not transalate
  if (dictionary[section] === undefined){
    return [section, word];
  }
  translatedWord = dictionary[section][word];
  return [section, translatedWord];
}

arrayToTransform = Object.keys(data.basic).map(key => translate(key, data.basic[key], engToHindi))
console.log(arrayToTransform)

transformed = arrayToObject(arrayToTransform);
console.log(transformed);

请确保您需要将字典分成几部分。