let object1 = {
a: 'somestring',
b: 42,
c: true,
d:{
e:1,
f:2,
g:true,
h:{
i:"hello"
}
},
j: [1,2,3],
k: ["foo", "bar"],
l:["foo",1,true],
m:[{n:10, o:"food", p:true }, {n:11, o:"foog", p:true }],
q:null,
r:undefined
};
let boolDefault = false;
let stringDefault = "";
let numberDefault = 0;
console.log(object1);
//document.write("<pre>");
//document.write(JSON.stringify(object1))
//document.write("<hr />");
cleanObject(object1);
console.log(object1);
//document.write(JSON.stringify(object1));
//document.write("</pre>");
function cleanObject(o) {
for (let [key, value] of Object.entries(o)) {
let propType = typeof(o[key]);
//console.log(key, value, propType);
switch (propType) {
case "number" :
o[key] = numberDefault;
break;
case "string":
o[key] = stringDefault;
break;
case "boolean":
o[key] = boolDefault;
break;
case "undefined":
o[key] = undefined;
break;
default:
if(value === null) {
continue;
}
cleanObject(o[key]);
break;
}
}
}
// EXPECTED OUTPUT
// Object { a: "somestring", b: 42, c: true, d: Object { e: 1, f: 2, g: true, h: Object { i: "hello" } }, j: Array [1, 2, 3], k: Array ["foo", "bar"], l: Array ["foo", 1, true], m: Array [Object { n: 10, o: "food", p: true }, Object { n: 11, o: "foog", p: true }], q: null, r: undefined }
// Object { a: "", b: 0, c: undefined, d: Object { e: 0, f: 0, g: undefined, h: Object { i: "" } }, j: Array [0, 0, 0], k: Array ["", ""], l: Array ["", 0, undefined], m: Array [Object { n: 0, o: "", p: undefined }, Object { n: 0, o: "", p: undefined }], q: null, r: undefined }