[英]Remove empty objects from an object
I am trying to remove empty objects inside an object, here is an example with the expected output:我正在尝试删除对象内的空对象,这是一个具有预期输出的示例:
var object = {
a: {
b: 1,
c: {
a: 1,
d: {},
e: {
f: {}
}
}
},
b: {}
}
var expectedResult = {
a: {
b: 1,
c: {
a: 1,
}
}
}
I tried using some examples from other StackOverflow questions, however those are just for one level objects.我尝试使用其他 StackOverflow 问题中的一些示例,但这些仅适用于一级对象。
Basic function that removes empty objects删除空对象的基本功能
First start with a function that only works with a single level of nesting.首先从一个仅适用于单层嵌套的函数开始。
This function removes all properties that reference an empty object:此函数删除引用空对象的所有属性:
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
}
return o;
}
}
Handling nested objects using recursion使用递归处理嵌套对象
Now you want to make it recursive so that it will operate on nested objects.现在您想让它递归,以便它可以对嵌套对象进行操作。 So we already have tested if o[k]
is an object, and we've tested if there are properties, so if there are, we simply call the function again with that nested object.所以我们已经测试了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
}
}
return o;
}
So just as the original call to clearEmpties
removes properties of the given object that reference an empty object, likewise the recursive call will do the same for the nested objects.因此,就像对clearEmpties
的原始调用删除了引用空对象的给定对象的属性一样,递归调用也会对嵌套对象执行相同的操作。
Live demo:现场演示:
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]; } } return o; }
Short version using Underscore and functional style使用下划线和功能风格的简短版本
function clearEmpties(o) {
if (_.isFunction(o) || !_.isObject(o)) return o;
return _.chain(o)
.mapObject(clearEmpties)
.pick(p => !(_.isObject(p) && _.isEmpty(p)))
.value();
}
I had this same problem and with the addition that my object may contain arrays with empty elements that need to be removed as well.我有同样的问题,另外我的对象可能包含需要删除的空元素的数组。
I ended up with this quick and dirty solution.我最终得到了这个快速而肮脏的解决方案。
If you want to define what "empty" means to you, I also added a different function.如果你想定义“空”对你意味着什么,我还添加了一个不同的功能。 In my case, I also needed empty strings.就我而言,我还需要空字符串。
function isEmpty(obj) {
if (obj === '' || obj === null || JSON.stringify(obj) === '{}' || JSON.stringify(obj) === '[]' || (obj) === undefined || (obj) === {}) {
return true
} else {
return false
}
}
function removeEmpty(o) {
if (typeof o !== "object") {
return o;
}
let oKeys = Object.keys(o)
for (let j = 0; j < oKeys.length; j++) {
let p = oKeys[j]
switch (typeof (o[p])) {
case 'object':
if (Array.isArray(o[p])) {
for (let i = 0; i < o[p].length; i++) {
o[p][i] = removeEmpty(o[p][i])
if (isEmpty(o[p][i])) {
o[p].splice(i, 1)
i--
}
}
if (o[p].length === 0) {
if (Array.isArray(o)) {
o.splice(parseInt(p), 1)
j--
} else {
delete o[p]
}
}
} else {
if (isEmpty(o[p])) {
delete o[p]
} else {
o[p] = removeEmpty(o[p])
if (isEmpty(o[p])) {
delete o[p]
}
}
}
break
default:
if (isEmpty(o[p])) {
delete o[p]
}
break
}
}
if (Object.keys(o).length === 0) {
return
}
return o
}
Input:输入:
var a = {
b: 1,
c: {
d: [1, [[], [], [[[1], []]]], [2, [[], [[]]]], [], [[]]]
},
e: {
f: [{}, { g: 1 }]
},
h: {
i: { j: { k: undefined, l: null, m: { n: "", o: 1 } } }
},
p: { q: { r: 1 } }
}
removeEmpty(a)
Output:输出:
{
"b": 1,
"c": {
"d": [1, [[[[1]]]], [2]]
},
"e": {
"f": [{"g": 1}]
},
"h": {
"i": {
"j": {
"m": {
"o": 1
}
}
}
},
"p": {
"q": {
"r": 1
}
}
}
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName]; }
}
}
EDIT:编辑:
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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.