如何在 Javascript 中更改嵌套字典中的键

How to change key in nested dictionary in Javacript

在编码世界中,我有一个格式为

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

如果我有

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

我如何更改键以便它删除 space 就像键“网络类型”是“网络类型”并将其添加回字典

{"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]
    }
}

这给我错误,我不知道 javaScript 也不知道如何访问密钥。

这会起作用

最好加上'_'或重命名为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)

之前

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

之后

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