如何删除JSON对象的键中的空间

时间:2016-11-25 11:52:17

标签: 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%"
  }]
}

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

ob = JSON.parse(output);

alert(Object.keys(ob))

当我这样做时,我将Newclassroom作为关键

3 个答案:

答案 0 :(得分:2)

您可以遍历您收到的对象中的顶级属性名称,使用空格检测任何名称,并删除空格。 (您不需要,它们是完全有效的属性名称,但如果您愿意,可以。)

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%的时间,没关系。如果在您的情况下很重要,请创建一个 new 对象,而不是在适当的位置进行修改:

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);

答案 1 :(得分:1)

  • 使用Object.keys获取对象的所有键
  • 使用String#replace替换String
  • 中的字符

var obj = {
  "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%"
  }]
};

Object.keys(obj).forEach(function(key) {
  var replaced = key.replace(' ', '');
  if (key !== replaced) {
    obj[replaced] = obj[key];
    delete obj[key];
  }
});
console.log(obj);

注意:只考虑单个空格,如果RegEx出现多次,则可以使用space

答案 2 :(得分:1)

循环json的每个键,然后解析。

试试regexp

var word = "New Classroom"
word = word.replace(/\s/g, '');
console.log(word)