JSFiddle - React, Tailwind, and code Playground
JavaScript
var json = {
"categoryID" : 1,
"categoryName" : "Stupid Questions",
"questions" : [{
"question" : {
"questionOptions" : [{
"questionOptionID" : 1,
"optionText" : "It's top secret."
}, {
"questionOptionID" : 2,
"optionText" : "Because I am big and your small. I am right and your wrong."
}, {
"questionOptionID" : 3,
"optionText" : "I will gladly pay you Tuesday for a hamburger today."
}
],
"questionType" : "checkbox",
"questionText" : "Why can't we use more abstract table and column names?",
"summary" : "Question of the year"
}
}]
}
function myTransform(string) {
// case-insensitive replace
return string.replace(/question/i,'template');
}
function transformObject(source) {
var result = {}
for( var key in source ) {
if( !source.hasOwnProperty(key) ) continue;
var value = source[key];
var newKey = myTransform(key);
if( Object.prototype.toString.call(value) == "[object Array]" ) {
result[newKey] = [];
for( var i in value ) {
if( !value.hasOwnProperty(i) ) continue;
result[newKey][i] = transformObject(value[i]);
}
}
else if( Object.prototype.toString.call(value) == "[object Object]" ) {
result[newKey] = transformObject(value);
}
else {
result[newKey] = value;
}
}
return result;
}
var wow = transformObject(json);
console.log( 'before:' );
console.log( json );
console.log( 'after:' );
console.log( wow );