javascript - 如何删除 JSON 对象的键中的空格

标签 javascript

我的输出如下:

output = {
  "New Classroom": [{
    "Name": "Apple",
    "Age": "6",
    "Percentage": "24.00%"
  }, {
    "Name": "Orange",
    "Age": "5",
    "Percentage": "9.88%"
  }, {
    "Name": "Green",
    "Age": "2",
    "Percentage": "27.27%"
  }, {
    "Name": "Grey",
    "Age": "6",
    "Percentage": "12.63%"
  }]
}

如何用 NewClassroom 替换 New Classroom,而新教室并不总是“NewClassroom”。它可能是不同的文本

ob = JSON.parse(output);

alert(Object.keys(ob))

当我这样做时,我将 Newclassroom 作为 key

最佳答案

您可以循环访问收到的对象中的顶级属性名称,检测任何带有空格的属性,然后删除空格。 (您不需要,它们是完全有效的属性名称,但如果您愿意,您可以。)

var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
var name, newName;
// Loop through the property names
for (var name in output) {
  // Get the name without spaces
  newName = name.replace(/ /g, "");
  // If that's different...
  if (newName != name) {
    // Create the new property
    output[newName] = output[name];
    // Delete the old one
    delete output[name];
  }
}
console.log(output);

请注意,对对象使用delete 会降低后续属性查找的性能。 99.99% 的情况下,这并不重要。如果这对您的情况很重要,请创建一个对象,而不是就地修改它:

var output = { "New Classroom": [{"Name": "Apple","Age": "6","Percentage": "24.00%"},{"Name": "Orange","Age": "5","Percentage": "9.88%"},{"Name": "Green","Age": "2","Percentage": "27.27%"},{"Name": "Grey","Age": "6","Percentage": "12.63%"}]};
var name, newName;
var newOutput = {};
// Loop through the property names
for (var name in output) {
  // Get the name without spaces
  newName = name.replace(/ /g, "");
  
  // Copy the property over
  newOutput[newName] = output[name];
}
console.log(newOutput);

关于javascript - 如何删除 JSON 对象的键中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40804436/

相关文章:

php - jquery twitter 插件,对 seo 友好

javascript - 如何在不移动鼠标的情况下加载页面时触发鼠标事件?

javascript - js比较二维数组

javascript - a = an; 有什么意义?分析 jQuery 源代码

javascript - 解构语法数组项和余数

javascript - 如何重用map函数中的对象?

javascript - 一个盒子不适合不同的屏幕分辨率

javascript - 从 Rails Assets 管道中清除缓存

javascript - 获取当前 YouTube 视频时间

javascript - Fabric JS 用相同的项目(ID)替换对象