I have an output like below:
output = {
\"New Classroom\": [{
\"Name\": \"Apple\",
\"Age\": \"6\",
\"Per
Object.keys
to get all keys of the objectString#replace
to replace character from 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);
Note: Only single occurrence of space is considered, RegEx
could be used if space
occurrence is more than once!
Loop in each keys of the json
, then parse.
try regexp
var word = "New Classroom"
word = word.replace(/\s/g, '');
console.log(word)
You can loop through the top-level property names in the object you receive, detect any with spaces, and remove the spaces. (You don't need to, they're perfectly valid property names, but you can if you want.)
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);
Note that using delete
on an object can reduce the performance of subsequent property lookups. 99.99% of the time, that doesn't matter. If it matters in your case, create a new object rather than modifying it in place:
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);