Skip to content

Instantly share code, notes, and snippets.

@danielo515
Last active June 9, 2017 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielo515/8812dd1dc7df0e6f86ab857db792be58 to your computer and use it in GitHub Desktop.
Save danielo515/8812dd1dc7df0e6f86ab857db792be58 to your computer and use it in GitHub Desktop.
A function that deletes empty object properties (null or undefined) and also deletes empty objects recursively. It is a small modification from https://stackoverflow.com/a/42736367/1734815
function valid(x){
return !( x == null || Number.isNaN(x));
}
function clearEmpties(o) {
for (const k in o) {
if (!valid(o[k])) {
delete o[k];
continue;
}
if (typeof o[k] !== 'object') {
continue;
}
clearEmpties( o[ k ] );
if (Array.isArray(o[k])){
o[k] = o[k].filter(valid);
}
if (Object.keys(o[k]).length === 0) {
delete o[k];
}
}
return o;
}
/** ========================= EXAMPLES ========================= **/
const dirty = {
key1: 'AAA',
key2: {
key21: 'BBB'
},
key3: {
key31: true,
key32: false
},
key4: {
key41: undefined,
key42: null,
key43: [],
key44: {},
key45: {
key451: NaN,
key452: {
key4521: {}
},
key453: [{ foo: {}, bar:'' }, NaN, null, undefined]
},
key46: ''
},
key5: {
key51: 1,
key52: ' ',
key53: [1, '2', {}, []],
key54: [{ foo: { bar: true, baz: null } }, { foo: { bar: '', baz: 0 } }]
},
key6: function () {}
};
const object = {
a: {
b: 1,
c: {
a: 1,
d: {},
e: { // will need to be removed after f has been removed
f: {},
z: {
w: null
},
y: []
}
}
},
b: {}
};
console.log(JSON.stringify(clearEmpties(object),null,2));
console.log(JSON.stringify(clearEmpties(dirty),null,2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment