在JavaScript对象中更改密钥名称 [英] Change key name in JavaScript object

查看:135
本文介绍了在JavaScript对象中更改密钥名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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]).

是由于我将密钥( Objects )转换为字符串(使用)替换方法)?

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

推荐答案

问题是你在原始对象中寻找属性使用新密钥。使用键[j] 而不是

The problem is that you are looking for the property in the original object using the new key. Use keys[j] instead of 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]];
}

我在替换中使用正则表达式,以便 ^ 可以匹配字符串的开头。这样它只会在它是前缀时替换字符串,并且不会将 noexample_data 转换为 no_data

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_data into no_data.

注意:你所拥有的不是一个json,它是一个JavaScript对象。 JSON是一种表示数据的文本格式。

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


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

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]];
   }
}

这篇关于在JavaScript对象中更改密钥名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆