在编码世界中,我有一个格式为
的数据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"}]}
我如何改变键,使它删除空格,如键"网络类型"是"network-type"并将其添加回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]
}
}
这是给我的错误,我不知道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" }] }