Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:41
Show Gist options
  • Save jherax/678090a964875f7c3539 to your computer and use it in GitHub Desktop.
Save jherax/678090a964875f7c3539 to your computer and use it in GitHub Desktop.
Deletes empty values from an Object or Array
var removeEmpty = (() => {
/**
* Determines if the entry parameter is not an object or array.
*
* @private
* @param {Any} v: the value to test
* @return {Boolean}
*/
const isNotObject = v => v === null || typeof v !== 'object';
/**
* Determines if the entry parameter is null or undefined.
*
* @private
* @param {Any} obj: object to test
* @return {Boolean}
*/
const isEmpty = obj => obj === null || obj === undefined;
/**
* Removes null and undefined values from an Object or Array.
*
* @export
* @param {Object | Array} obj: the object to where remove the empty values
* @return {Any}
*/
return function(obj) {
if (isNotObject(obj)) return obj;
if (obj instanceof Array) {
for (let i = 0; i < obj.length; i += 1) {
if (isEmpty(obj[i])) obj.splice(i--, 1); // eslint-disable-line
else removeEmpty(obj[i]);
}
} else {
for (const p in obj) {
if (isEmpty(obj[p])) delete obj[p];
else removeEmpty(obj[p]);
}
}
return obj;
};
})();
/**
* Remove empty objects or arrays.
*
* @export
* @param {Object | Array} obj: the object to where remove empty objects or arrays.
* @return {Any}
*/
var removeEmptyObject = (() => {
const isNotObject = v => v === null || typeof v !== 'object';
const isEmpty = obj => Object.keys(obj).length === 0;
return (obj) => {
if (isNotObject(obj)) return obj;
if (obj instanceof Array) {
for (let i = 0; i < obj.length; i += 1) {
if (isNotObject(obj[i])) continue;
if (isEmpty(obj[i])) obj.splice(i--, 1); // test again at same index
else obj[i] = removeEmptyObject(obj[i]);
}
} else {
for (const p in obj) {
if (isNotObject(obj[p])) continue;
if (!isEmpty(obj[p])) obj[p] = removeEmptyObject(obj[p]);
if (isEmpty(obj[p])) delete obj[p]; // ensures obj[p] is not empty
}
}
return obj;
};
})();
// TEST: removeEmpty
var arr = [1, null, null, 4, null, 6];
hc.removeEmpty(arr);
console.log(arr);
arr = [[2, null, 6], [undefined, null, 9], [[null, 3], 7, undefined]];
hc.removeEmpty(arr);
console.log(JSON.stringify(arr));
var obj = { hola: undefined, id: 1, info: null, name: 'pepe', age: 0 };
hc.removeEmpty(obj);
console.log(obj);
// TEST: removeEmptyObject
var json = '{"test": [{},{},{"x": 1}], "test2": [{},{}], "test3":[[],[1,2,3],[]], "a": 1, "b": 2}';
var data = JSON.parse(json);
removeEmptyObject(data);
console.log(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment