Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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]
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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];
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda