如何在Javascript键中替换/命名键:值对象? [英] How to replace/name keys in a Javascript key:value object?

查看:75
本文介绍了如何在Javascript键中替换/命名键:值对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何替换Javascript键中的键字符串:值哈希映射(作为对象)?

How should I replace the key strings in a Javascript key:value hash map (as an object)?

这是我到目前为止所拥有的:

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

看到它在 jsbin

之前和之后的哈希图是相同的,所以 forEach 似乎在不同的范围内。我该如何解决?也许有更好的方法可以做到这一点?

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?

推荐答案

它与范围无关。 key 只是一个局部变量,它不是实际对象键的别名,因此分配它不会改变对象。

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.

Object.keys(hashmap).forEach(function(key) {
  var newkey = key + "xxx";
  hashmap[newkey] = hashmap[key];
  delete hashmap[key];
});

这篇关于如何在Javascript键中替换/命名键:值对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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