'Not able to change keys in JavaScipt dictionary

I am a beginner, I want to replace spaces with hyphen from keys of JavaScript dictionary and get the keys back in dictionary

eg. In nameVars = {"my name is":"aman", "age":22, "my ed":"btech"} I want resultant dictionary to be, nameVars = {"my-name-is":"aman", "age":22, "my-ed":"btech"} I am doing it using

for(const [key, value] of Object.entries(nameVars)){
  key.replace(/\s+/g,"-")`
}

But my output is still same keys are not changing, please help I don't know JavaScript.

Can someone tell what changes to make if instead this it is in format

topicMessage = { topic: 'some_topic', messages: [{ 'myKey': '{"data": {"my name is ":"aman", "age": 22, "my ed": "btech"}, "meta": {"myAge":24, "school":"aps"}}' }, { 'myKey2': '{ "data": { "my name is 2": "aman", "age": 22, "my ed 2": "btech" }, "meta": { "myAge2": 24, "school": "aps" } } ' }, { "myKey3": '{"data": {"my name is 3":"aman", "age": 22, "my ed 3": "btech"}, "meta": {"myAge":24, "school":"aps"}}' } ] }

here inside messaages of topicMessages in data part we have to make keys dash separated, and value for mykey, mykey2, mykey3 are in string form, so need to convert JSON.parse to object first and then again convert it back to string.



Solution 1:[1]

You should replace the content of the Object

var nameVars = {"my name is":"aman", "age":22, "my ed":"btech"}

for (const [key, value] of Object.entries(nameVars)) {
  if(key.includes(" ")){
    const newKey = key.replace(/\s+/g,"-")
    nameVars[newKey] = value;
    delete nameVars[key]
  }
}

Solution 2:[2]

You modify the names of the keys but never add the modified keys back to to the object. You can approach your problem like this:

for(const [oldKey, value] of Object.entries(nameVars)){    
    const newKey = oldKey.replace(/\s+/g,"-");
    // add the entry with the new key
    nameVars[newKey] = value;
    // delete the old entry
    delete nameVars[oldKey];
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MatthewSaintbull
Solution 2 Dieter Raber