Home > Software engineering >  How to change key in nested dictionary in Javacript
How to change key in nested dictionary in Javacript

Time:05-06

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.

CodePudding user response:

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