Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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?

like image 513
HaoQi Li Avatar asked Jul 09 '13 03:07

HaoQi Li


People also ask

How do I change the type of key in an object?

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.

How do you modify an object in JavaScript?

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.

Can JavaScript object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


2 Answers

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];
});
like image 166
Barmar Avatar answered Oct 24 '22 16:10

Barmar


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.

like image 21
Ori Lerman Avatar answered Oct 24 '22 16:10

Ori Lerman