我的输出如下:
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/