Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created June 1, 2018 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleybliss/9f6aa453afaec5851ab2bce4c15ef11b to your computer and use it in GitHub Desktop.
Save wesleybliss/9f6aa453afaec5851ab2bce4c15ef11b to your computer and use it in GitHub Desktop.
Filters an object returning only properties specified
/**
* Filters an object returning only properties specified
*
* @param {Object} obj Source object
* @param {Array} keys List of (strings) properties to keep
* @return {Object} Object with only props specified in `keys`
*/
export const filterKeys = (obj, keepKeys, dropKeys) => {
if (typeof obj !== 'object')
throw new Error('Param `obj` must be an object')
const okeys = Object.keys(obj)
const keep = keepKeys || okeys
const drop = dropKeys || []
if (!(keep instanceof Array))
throw new Error('Param `keepKeys` must be an array')
if (!(drop instanceof Array))
throw new Error('Param `dropKeys` must be an array')
if (!keep.length && !drop.length)
throw new Error('Either param `keepKeys` or `dropKeys` must contain more than one key')
return okeys
.reduce((result, it) => {
if (!keep.includes(it) || drop.includes(it)) return result
return [...result, it]
}, [])
.reduce((result, it) => ({
...result,
[it]: obj[it]
}), {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment