Home > Mobile >  Not able to change keys in JavaScipt dictionary
Not able to change keys in JavaScipt dictionary

Time:05-05

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 dont know javascript.

CodePudding user response:

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

CodePudding user response:

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]
  }
}
  • Related