Created
July 4, 2022 09:44
-
-
Save jkohlin/751e21856f14464892ad45a8b4e49b15 to your computer and use it in GitHub Desktop.
A function to filter an object based on another object, or array. Filter either by key or by value, including or excluding.
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
/** | |
* Description: Remove properties from an object based on a filter | |
* @param {object} obj The object to filter out elements from | |
* @param {[string]|object} filter The array, or object to use as filter | |
* @param {boolean} filterIsKey (default true) wether the filter is referring to the key or the value | |
* @param {boolean} inclusive (default true) wether the filter is what we want to keep, or what we want to remove | |
* @returns {object} A new filtered object | |
*/ | |
function objectFilter (obj, filter, filterIsKey = true, inclusive = true) { | |
return Array.isArray(filter) | |
? Object.fromEntries(Object.entries(obj).filter(([key, value]) => inclusive ? filter.includes(filterIsKey ? key : value) : !filter.includes(filterIsKey ? key : value))) | |
: Object.fromEntries(Object.entries(obj).filter(([key, value]) => inclusive ? Object.keys(filter).includes(filterIsKey ? key : value): !Object.keys(filter).includes(filterIsKey ? key : value))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment