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);
See it running in this 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?
Advertisement
Answer
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]; });