How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:
[{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}]
I want to be able to dynamically rename "FIRST NAME" and "LAST NAME" to "FIRST_NAME" and "LAST_NAME" respectively. Based on research so far, I have this function:
function replaceSpaces(data) {
debugger;
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
var replacedKey = key.split(' ').join('_');
data[i][obj] = replacedKey;
}
}
return data;
}
The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.
My issue with this code is that it's looping through the keys just fine, and assigning the proper replaced string to "replacedKey", but it's not assigning that to the original data object.
Here's complete code using forEach
.
The steps are same as Quentin has stated in his answer
var arr = [{
"FIRST NAME": "Philip",
"LAST NAME": "Rivers",
"NUMBER": "17",
"GPA": "1.0",
"OLD_FACTOR": "8",
"NICENESS": "1"
}, {
"FIRST NAME": "Peyton",
"LAST NAME": "Manning",
"NUMBER": "18",
"GPA": "4.0",
"OLD_FACTOR": "5000",
"NICENESS": "5000"
}];
// Iterate over array
arr.forEach(function(e, i) {
// Iterate over the keys of object
Object.keys(e).forEach(function(key) {
// Copy the value
var val = e[key],
newKey = key.replace(/\s+/g, '_');
// Remove key-value from object
delete arr[i][key];
// Add value with new key
arr[i][newKey] = val;
});
});
console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>
Strictly if the JSON is get in the form of String from server:
Replace the spaces by _
from the keys.
JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
return m.replace(/\s+/g, '_');
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With