Skip to content

Instantly share code, notes, and snippets.

@ivanhoe011
Last active October 9, 2024 10:38
Show Gist options
  • Save ivanhoe011/c311291f7b628c7d3aed6180b7111a64 to your computer and use it in GitHub Desktop.
Save ivanhoe011/c311291f7b628c7d3aed6180b7111a64 to your computer and use it in GitHub Desktop.
Filter out empty properties from the object
/**
* Helper to filter out the empty properties(null, undefined, [], or '') from the given object
*
* @param {{}} obj
* @returns {{}}
*/
const removeEmptyProps = (obj) => {
return Object.keys(obj)
// remove params that are empty
.filter(key => {
const emptyArray = (Array.isArray(obj[key]) && obj[key].length === 0);
const emptyVal = (obj[key] === '' || obj[key] === null || obj[key] === undefined);
return ! (emptyArray || emptyVal);
})
// create the filtered object
.reduce((acc, key) => { acc[key] = obj[key]; return acc; }, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment