Created
June 1, 2018 06:30
-
-
Save wesleybliss/9f6aa453afaec5851ab2bce4c15ef11b to your computer and use it in GitHub Desktop.
Filters an object returning only properties specified
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
/** | |
* 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