更改 JavaScript 对象中的键名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32452014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:04:05  来源:igfitidea点击:

Change key name in JavaScript object

javascript

提问by johnmalkovitch

I am checking the attributes in a JavaScript object, replacing some of the keys by deleting the prefix "element" and saving the new values in another object.

我正在检查 JavaScript 对象中的属性,通过删除前缀“元素”并将新值保存在另一个对象中来替换某些键。

var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
   key = keys[j].replace("element_", "");
   switch(key) {
   default :
      tmp[key] = json[key];
      break;
   }
}

The matter is that when I do that, I can log all the keys, they have the correct names, but when I try to set the values associated to these keys, they are undefined (json[key]).

问题是,当我这样做时,我可以记录所有键,它们具有正确的名称,但是当我尝试设置与这些键关联的值时,它们是未定义的 (json[key])。

Is that due to the fact that I converted the keys (Objects) to Strings(with the replacemethod)?

这是因为我将键 ( Objects)转换为Strings(使用replace方法) 吗?

采纳答案by Guffa

The problem is that you are looking for the property in the original object using the new key. Use keys[j]instead of key:

问题是您正在使用新键在原始对象中查找属性。使用keys[j]代替key

var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
   var key = keys[j].replace(/^element_/, "");
   tmp[key] = json[keys[j]];
}

I uses a regular expression in the replace so that ^can match the beginning of the string. That way it only replaces the string when it is a prefix, and doesn't turn for example noexample_datainto no_data.

我在替换中使用了正则表达式,以便^可以匹配字符串的开头。这样,当它是一个前缀,不转例如,只替换字符串noexample_datano_data

Note: What you have is not "a json", it's a JavaScript object. JSON is a text format for representing data.

注意:您拥有的不是“一个 json”,而是一个 JavaScript 对象。JSON 是一种用于表示数据的文本格式。

Is that due to the fact that I converted the keys (Objects) to Strings (with the replace method)?

这是因为我将键(对象)转换为字符串(使用替换方法)吗?

No. The keys are strings, not objects.

不。键是字符串,而不是对象。



You could also change the properties in the original object by deleting the old ones and adding new:

您还可以通过删除旧对象并添加新对象来更改原始对象中的属性:

var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
   if (keys[j].indexOf("element_") == 0) {
     json[keys[j].substr(8)] = json[keys[j]];
     delete json[keys[j]];
   }
}

回答by

We'll write a little function to fix the key the way you want.

我们将编写一个小函数来按照您想要的方式修复密钥。

function fix_key(key) { return key.replace(/^element_/, ''); }

Underscore

下划线

_.object(
  _.map(_.keys(json), fix_key),
  _.values(json)
)

ES5/loop

ES5/循环

var keys = Object.keys(json);
var result = {};

for (i = 0; i < keys.length; i++) {
  var key = keys[i];
  result[fix_key(key)] = json[key];
}

return result;

ES5/reduce

ES5/减少

Object.keys(json) . reduce(function(result, key) {
  result[fix_key(key)] = json[key];
  return result;
}, {});

ES6

ES6

Object.assign(
  {},
  ...Object.keys(json) .
    map(key => ({[fix_key(key)]: json[key]}))
)

This makes an array of little objects each with one key-value pair, using the ES6 "computed property name" feature, then passes them to Object.assignusing the ES6 "spread" operator, which merges them together.

这使用 ES6 的“计算属性名称”功能创建了一个小对象数组,每个对象都有一个键值对,然后将它们传递给Object.assign使用 ES6 的“扩展”运算符,后者将它们合并在一起。

回答by num8er

Try this:

尝试这个:

var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
   var key = keys[j]; // key
   var value = json[key]; // data
   delete json[key]; // deleting data with old key
   key = key.replace("element_", ""); // renaming key
   json[key] = value; // setting data with new key
}

回答by ozil

keyis not original jsonbecause you have remove element_prefix

key不是原创的,json因为您删除了element_前缀

var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
   key = keys[j].replace("element_", "");
   var _key = keys[j];
   switch(key) {
   default :
      tmp[key] = json[_key];
      break;
   }
}