Last active
October 9, 2024 10:38
-
-
Save ivanhoe011/c311291f7b628c7d3aed6180b7111a64 to your computer and use it in GitHub Desktop.
Filter out empty properties from the object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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