无法更改 JavaScript 字典中的键

Not able to change keys in JavaScipt dictionary

我是初学者,我想用 JavaScript 字典的键中的连字符替换空格,然后将键取回字典中

例如。在 nameVars = {"my name is":"aman", "age":22, "my ed":"btech"} 我希望生成的字典是 nameVars = {"my-name-is":"aman", "age":22, "my-ed":"btech"} 我正在使用

for(const [key, value] of Object.entries(nameVars)){
  key.replace(/\s+/g,"-")`
}

但我的输出仍然是相同的键没有改变,请帮助我不知道JavaScript。

有人可以告诉我要进行哪些更改,如果不是这种格式

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

这里在数据部分的topicMessages的messaages里面我们要让keys用破折号分隔,mykey,mykey2,mykey3的value都是字符串形式的,所以需要先把JSON.parse转成object再转它回到字符串。

您修改了键的名称,但从未将修改后的键添加回对象。您可以这样解决您的问题:

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];
}

您应该替换对象的内容

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