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?
Personally, the most effective way to rename keys in object without implementing extra heavy plugins and wheels: var str = JSON. stringify(object); str = str. replace(/oldKey/g, 'newKey'); str = str.
Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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];
});
if keys order is important you can use:
const clone = Object.fromEntries(
Object.entries(o).map(([o_key, o_val]) => {
if (o_key === key) return [newKey, o_val];
return [o_key, o_val];
})
);
this will create an object with the new key in the same place where the old one was.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With