示例:
let anyObject = {
name: 'Any name',
address: [{
street: null, // should exclude
city: 'any city',
state: 'any state'
}, {}],
otherObject: {
otherProperty: {
value: {
value1: 1,
value2: {} // should exclude
}
}
}
}
removeAllPropertyWithoutValue(anyObject)
存在一些有效的算法吗?我尝试使用_.pick
,但仅限于第一级深度对象。
答案 0 :(得分:3)
这应该符合您的期望:
var anyObject = {
name: 'Any name',
address: [{
street: null,
city: 'any city',
state: 'any state'
}, {}],
otherObject: {
otherProperty: {
value: {
value1: 1,
value2: {}
}
}
}
}
function cleanUp(obj) {
Object.keys(obj).reverse().forEach(function(k) {
if(obj[k] === null || obj[k] === undefined) {
obj instanceof Array ? obj.splice(k, 1) : delete obj[k];
}
else if(typeof obj[k] == 'object') {
cleanUp(obj[k]);
if(Object.keys(obj[k]).length == 0) {
obj instanceof Array ? obj.splice(k, 1) : delete obj[k];
}
}
});
}
cleanUp(anyObject);
console.log(anyObject);