如何替换/命名 Javascript key:value 对象中的键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17539236/
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
How to replace/name keys in a Javascript key:value object?
提问by HaoQi Li
How should I replace the key strings in a Javascript key:value hash map (as an object)?
我应该如何替换 Javascript key:value 哈希映射中的键字符串(作为对象)?
This is what I have so far:
这是我到目前为止:
var hashmap = {"aaa":"foo", "bbb":"bar"};
console.log("before:");
console.log(hashmap);
Object.keys(hashmap).forEach(function(key){
key = key + "xxx";
console.log("changing:");
console.log(key);
});
console.log("after:");
console.log(hashmap);
See it running in this jsbin.
看看它在这个jsbin 中运行。
The "before" and "after" hashmaps are the same, so the forEach
seems to be in a different scope. How can I fix it? Perhaps there are better ways of doing this?
“之前”和“之后”哈希图是相同的,因此forEach
似乎在不同的范围内。我该如何解决?也许有更好的方法来做到这一点?
回答by Barmar
It has nothing to do with scope. key
is just a local variable, it's not an alias for the actual object key, so assigning it doesn't change the object.
它与范围无关。key
只是一个局部变量,它不是实际对象键的别名,因此分配它不会更改对象。
Object.keys(hashmap).forEach(function(key) {
var newkey = key + "xxx";
hashmap[newkey] = hashmap[key];
delete hashmap[key];
});
回答by Finian Lau
You are just changing the copyof the object's keys, so the original object won't be changed. You can create an new object to hold the new keys, like this:
您只是更改对象键的副本,因此不会更改原始对象。您可以创建一个新对象来保存新键,如下所示:
var hashmap = {"aaa":"foo", "bbb":"bar"};
console.log("before:");
console.log(hashmap);
var newHashmap = {};
Object.keys(hashmap).forEach(function(key){
var value = hashmap[key];
key = key + "xxx";
console.log("changing:");
console.log(key);
newHashmap[key] = value;
});
console.log("after:");
console.log(newHashmap);