Delete Null Values In Nested Javascript Objects
I have a nested object and want to remove all key/value pairs if the value is null or undefined. I've managed to get the below code working but it doesn't check the nested key/valu
Solution 1:
You're already almost there. Just have the function recurse if the property is another object:
var myObj = {
fName:'john',
lName:'doe',
dob:{
displayValue: null,
value: null
},
bbb:null
};
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
delete obj[propName];
} else if (typeof obj[propName] === "object") {
// Recurse here if the property is another object.
clean(obj[propName])
}
}
return obj;
}
console.log(clean(myObj));
Post a Comment for "Delete Null Values In Nested Javascript Objects"