Skip to content

Instantly share code, notes, and snippets.

@adover
Created December 7, 2018 01:02
Show Gist options
  • Save adover/3ba0cd86a07b0a86af0ec573eb768d0a to your computer and use it in GitHub Desktop.
Save adover/3ba0cd86a07b0a86af0ec573eb768d0a to your computer and use it in GitHub Desktop.
Admin for objects
/**
* Triggers all the methods below it to return a nicely
* formatted object.
* @param args
*/
sanitise(args) {
const flatParams = this.flatten(args);
const cleanParams = this.clean(flatParams);
return this.parseDates(cleanParams);
}
/**
* Takes an object with empty or null items and removes them
*
* @param o: Object
*/
clean = o => {
Object.keys(o).forEach(k => !o[k] && delete o[k]);
return o;
}
/**
* Takes a nested object and flattens it into an array
*
* @param o: Object
*/
flatten = o =>
Object.assign(
{},
...(function _flatten(internalO) {
return [].concat(
...Object.keys(internalO).map(k =>
typeof internalO[k] === 'object' && !(internalO[k] instanceof Date)
? _flatten(internalO[k])
: { [k]: internalO[k] },
),
);
})(o || {}),
)
/**
* Converts any dates into the object into UTC ISO strings
*
* @param o: Object
*/
parseDates = o => {
Object.keys(o).forEach(k => {
o[k] = o[k] instanceof Date ? new Date(o[k]).toISOString() : o[k];
});
return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment