Geo*_*lov 3 javascript node.js underscore.js
我试图删除对象内的空对象,这是一个具有预期输出的示例:
var object = {
a: {
b: 1,
c: {
a: 1,
d: {},
e: {
f: {}
}
}
},
b: {}
}
var expectedResult = {
a: {
b: 1,
c: {
a: 1,
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用其他StackOverflow问题中的一些示例,但这些只是针对一个级别的对象.
小智 10
删除空对象的基本功能
首先使用仅适用于单级嵌套的函数.
此函数删除引用空对象的所有属性:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用递归处理嵌套对象
现在你想让它递归,以便它可以在嵌套对象上运行.所以我们已经测试过if是否o[k]是一个对象,并且我们已经测试了是否有属性,所以如果有,我们只需用该嵌套对象再次调用该函数.
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,正如原始调用clearEmpties删除引用空对象的给定对象的属性一样,递归调用也会对嵌套对象执行相同操作.
现场演示:
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];
}
}
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5352 次 |
| 最近记录: |