• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

224
Vistas
How to change key in nested dictionary in Javacript

in coding world, I have a data in format of

knownMessages : {
    topic:string, 
    messages: Array<{
        key: string;
        value;
        sum_num: number;
        headers: Map<string, string>;
    }>;
}[]

if i have

knownMessages = {topic:"some_topic", messages: [{"network type":"lan"}, {"agent": "aman"},{    "my ed":"btech"}]}

How can i changes keys such that it removes space like key "network type" is "network-type" and also add it back to dictionary

{"network-type": "lan", {"agent": "aman"}, {"my-ed": "btech"}}
for(let i = 0; i < knownMessages.messages.length; i++){
    if(knownMessages.message[i][key].include(" ")){
        const newKey = key.replace(/\s+/g, "-");
        knownMessages.messages[i][newKey] = value;
        delete topicMessage.messages[i][key]
    }
}

This is giving me errors, i dont know javaScript and dont know how to access keys.

over 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

this will work

it will be better to add '_' or rename it to camalcase

knownMessages = {topic:"some_topic",
                 messages: [
                   {"network type":"lan"},
                   {"agent": "aman"},
                   {    "my ed":"btech"}
                 ]
                }

console.log(knownMessages)
for(let i = 0; i < knownMessages.messages.length; i++){
   key =Object.keys(knownMessages.messages[i])[0]


    if(key.includes(" ")){
    const newKey = key.replace(/\s+/g, "_");  
    knownMessages.messages[i][newKey] = knownMessages.messages[i]key]
    delete knownMessages.messages[i][key]
    }
}
console.log(knownMessages)

before

Object { topic: "some_topic", messages: Array [Object { network type: "lan" }, Object { agent: "aman" }, Object { my ed: "btech" }] }

after

Object { topic: "some_topic", messages: Array [Object { network-type: "lan" }, Object { agent: "aman" }, Object { my-ed: "btech" }] }
over 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda