删除嵌套javascript对象中的空值 [英] Delete null values in nested javascript objects
问题描述
我有一个嵌套的对象,并且想要删除所有键/值对,如果值是null或未定义.我设法使下面的代码正常工作,但是它没有检查嵌套的键/值对,并想知道是否有人可以帮助我找出需要添加到代码中的内容?
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));
上面的代码完成了删除"bbb"及其值的工作,我也希望对以"dob"表示的嵌套对象执行相同的操作.
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.
推荐答案
您已经快要准备好了.如果该属性是另一个对象,只需让函数递归:
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));
这篇关于删除嵌套javascript对象中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!