How to replace / name keys in a Javascript key: value map?

How to replace key strings in a Javascript key: hash map 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 how this jsbin works .

The characters "before" and "after" are the same, so forEach appears in a different volume. How can i fix this? Perhaps there are better ways to do this?

+6
source share
2 answers

This has nothing to do with scope. key is only a local variable, it is not an alias for the actual key of the object, so assigning it does not change the object.

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

You simply change the copy of the keys of the object, so the original object will not be changed. You can create a new object to store new keys, for example:

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

Source: https://habr.com/ru/post/948989/


All Articles