更新时间:2023-09-02 21:32:34
试试下面代码,没用函式库,直接作两次递回,第一次去空字串,第二次是去空对象,没细测过大量资料时的效能,但可得出你要的结果。再深层一些可再试试:
function isEmpty(obj) {
return (Object.keys(obj).length === 0 && obj.constructor === Object);
}
function deleteEmptyString(test, recurse) {
for (var i in test) {
if (test[i] === '' ) {
delete test[i];
} else if (recurse && typeof test[i] === 'object') {
deleteEmptyString(test[i], recurse);
}
}
}
function deleteEmptyObject(test, recurse) {
for (var i in test) {
if (isEmpty(test[i]) ) {
delete test[i];
} else if (recurse && typeof test[i] === 'object') {
deleteEmptyObject(test[i], recurse);
}
}
}
var o = {
a:1,
b:{b_a:''},
c:{c_a:1,c_b:''},
//d:{d_a:1,d_b:'', d_c: { x:'', y:1}, d_d:{ z:'' } }
}
deleteEmptyString(o, true);
console.log(o);
deleteEmptyObject(o,true);
console.log(o);