从对象中删除空对象

我试图删除对象内的空对象,这是一个预期的输出示例:

var object = { a: { b: 1, c: { a: 1, d: {}, e: { f: {} } } }, b: {} } var expectedResult = { a: { b: 1, c: { a: 1, } } } 

我尝试使用其他StackOverflow问题的一些例子,但是这些只是一个级别的对象。

删除空对象的基本function

首先从一个函数开始,这个函数只适用于单层嵌套。

该函数删除引用空对象的所有属性:

 function clearEmpties(o) { for (var k in o) { if (!o[k] || typeof o[k] !== "object") { continue // If null or not an object, skip to the next iteration } // The property is an object if (Object.keys(o[k]).length === 0) { delete o[k]; // The object had no properties, so delete that property } } } 

使用recursion处理嵌套的对象

现在你想让它recursion,以便它可以在嵌套对象上运行。 所以我们已经testing过,如果o[k]是一个对象,并且我们已经testing了是否有属性,所以如果有的话,我们只需再次调用该嵌套对象的函数。

 function clearEmpties(o) { for (var k in o) { if (!o[k] || typeof o[k] !== "object") { continue // If null or not an object, skip to the next iteration } // The property is an object clearEmpties(o[k]); // <-- Make a recursive call on the nested object if (Object.keys(o[k]).length === 0) { delete o[k]; // The object had no properties, so delete that property } } } 

所以就像原来的clearEmpties调用去掉引用空对象的给定对象的属性一样,recursion调用对嵌套对象也是一样的。


现场演示:

 var object = { a: { b: 1, c: { a: 1, d: {}, e: { // will need to be removed after f has been removed f: {} } } }, b: {} }; clearEmpties(object); console.log(object); function clearEmpties(o) { for (var k in o) { if (!o[k] || typeof o[k] !== "object") { continue } clearEmpties(o[k]); if (Object.keys(o[k]).length === 0) { delete o[k]; } } } 
 function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } } 

编辑:

 function clean(obj) { for (var propName in obj) { if(typeof obj[propName]=="object") clean(obj[propName]) if (obj[propName] === null || obj[propName] === undefined) delete obj[propName]; } }