问题
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/value pairs and wondered if someone could help me figure out what needs adding to the code please?
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];
}
}
return obj;
}
console.log(clean(myObj));
The above code does the job to remove 'bbb' and its value and I want the same done for the nested object represented by 'dob' as well.
https://jsbin.com/mudirateso/edit?js,console,output
Any help is greatly appreciated.
回答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));
来源:https://stackoverflow.com/questions/47296396/delete-null-values-in-nested-javascript-objects