Firstly lets combine some knowledge:
How do I test for an empty JavaScript object?
The above question has an awesome answer with many options in it, I'm going to edit the snippets to form a couple of functions:
function isObject (obj) {
return obj.constructor === Object;
}
function isEmptyObject (obj) {
return Object.keys(obj).length === 0 && isObject(obj);
}
Ace. Now, assuming you have a very linear object structure, it's not a complex array and don't care about the depth (only that it is empty) lets make a function loop through the tree.
function convertEmptyObjects (obj, currentDepth) {
currentDepth = currentDepth || 0;
for (var key in obj) {
var val = obj[key];
if (isObject(val)) {
if (isEmptyObject(val)) {
obj[key] = "{}";
console.log("Defeated boss ("+ key +") on level "+ currentDepth +"!");
}else{
convertDeepestEmptyObject (val, currentDepth + 1);
}
}
}
return obj;
}
Lets test this on an awful looking object:
var testObject = {
CONN_INFO: {
CFGSwitch: {
412: {}, // Level 2
413: {
content: {} // Level 3
}
},
DummySwitch: {} // Level 1
},
TEST_CONN_INFO: {
CFGSwitch: {
414: {}, // Level 2
415: {
content: {
host: "google",
port: "8080",
protocol: {} // Level 4
}
}
}
},
STAGING_CONN_INFO: {} // Level 0
}
convertEmptyObjects(testObject);
JSON.stringify(testObject)
/* Output:
* Defeated boss (412) on level 2!
* Defeated boss (content) on level 3!
* Defeated boss (DummySwitch) on level 1!
* Defeated boss (414) on level 2!
* Defeated boss (protocol) on level 4!
* Defeated boss (STAGING_CONN_INFO) on level 0!
*/
// Result:
{
"CONN_INFO": {
"CFGSwitch": {
"412": "{}", // Empty String {}
"413": {
"content": "{}" // Empty String {}
}
},
"DummySwitch": "{}" // Empty String {}
},
"TEST_CONN_INFO": {
"CFGSwitch": {
"414": "{}", // Empty String {}
"415": {
"content": {
"host": "google",
"port": "8080",
"protocol": "{}" // Empty String {}
}
}
}
},
"STAGING_CONN_INFO": "{}" // Empty String {}
}
There you have it.