Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save snobu/7dbee9a5fc43c6c664b73409bb2f7f88 to your computer and use it in GitHub Desktop.

Select an option

Save snobu/7dbee9a5fc43c6c664b73409bb2f7f88 to your computer and use it in GitHub Desktop.
Javascript (Typescript): Remove empty properties from object
deleteEmptyProps(obj: any): any {
// modifies passed obj in place, removing empty properties (inc. empty arrays)
return Object.keys(obj).forEach(k => {
if (!obj[k] || obj[k] === undefined ||
Array.isArray(obj[k]) && obj[k].length === 0) {
delete obj[k];
}
});
}
@asins
Copy link

asins commented Dec 22, 2023

let obj = {
a: 0,
b: false,
c: '',
d: [],
};
deleteEmptyProps(obj) // obj = {e: 333}

a = 0 // It should also be a valid value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment