简体   繁体   English

如何更改 json 对象的所有属性名称

[英]How to change all the property names of a json object

I would like to change all the property names of a json object我想更改 json 对象的所有属性名称

const obj = {
  "country": "Value1",
  "area": "value2",
  "color_flag": "value3"
}

const newKeys = ["pays", "Superficie", "Couleur de drapeau"]

// I would like to have something like this : 

obj = {
  "pays": "Value1",
  "superficie": "Value2",
  "couleur_drapeau": "Value3"
}

Thanks in advance提前致谢

You can clone your object using new keys, but you need to provide a map for your new keys like this:您可以使用新键克隆您的对象,但您需要为新键提供一个映射,如下所示:

const newKeys = {
  "country": "pays",
  "area": "superficie",
  "color_flag": "couleur_drapeau"
}

Simply on the left put the original key, and on the right put the new one that in your case is the translation to french.只需在左侧放置原始密钥,在右侧放置新密钥,就您而言,它是法语翻译。

Then you need to loop over all keys of your original object and copy each value to the new object with the new key然后您需要遍历原始对象的所有键,并使用新键将每个值复制到新对象

const renamedObj = {}
for(let key in obj){
  const newKey = newKeys[key]
  renamedObj[newKey] = obj[key]
}

Final code should be like this:最终代码应该是这样的:

const obj = {
  "country": "Value1",
  "area": "value2",
  "color_flag": "value3"
}

const newKeys = { // Keys map
  "country": "pays",
  "area": "superficie",
  "color_flag": "couleur_drapeau"
}

const renamedObj = {}
for(let key in obj){
  const newKey = newKeys[key]
  renamedObj[newKey] = obj[key]
}

renamedObj should look like this: renamedObj应该是这样的:

renamedObj = {
  "pays": "Value1",
  "superficie": "Value2",
  "couleur_drapeau": "Value3"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM