Skip to content

Instantly share code, notes, and snippets.

@jjherscheid
Created May 30, 2022 09:32
Show Gist options
  • Save jjherscheid/baa816d83ea4ca4d7c9a2d6c4544465a to your computer and use it in GitHub Desktop.
Save jjherscheid/baa816d83ea4ca4d7c9a2d6c4544465a to your computer and use it in GitHub Desktop.
import _ from "lodash";
/** This method can be used to simplify objects with empty properties. propX: undefined of propX: {} will be removed */
const compact = (obj: any): any => {
return _(obj)
.mapValues((propertyValue) => {
if (!_.isObject(propertyValue)) {
return propertyValue;
} else if (_.isArray(propertyValue)) {
return propertyValue.map((arrayItem) => {
if (_.isObject(arrayItem)) {
return compact(arrayItem);
} else {
return arrayItem;
}
});
} else {
return compact(propertyValue);
}
})
.omitBy((value) => _.isNil(value) || _.isEmpty(value))
.value();
};
export const objectsHelper = {
compact
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment