Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  100] [ 6]  / answers: 1 / hits: 71703  / 11 Years ago, tue, july 9, 2013, 12:00:00

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?


More From » javascript

 Answers
3

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

[#77124] Sunday, July 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalistaz

Total Points: 0
Total Questions: 100
Total Answers: 106

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;