Skip to content

Instantly share code, notes, and snippets.

@jkohlin
Created December 19, 2022 09:36
Show Gist options
  • Save jkohlin/10d07b786d3624df9560bb23a1d8f151 to your computer and use it in GitHub Desktop.
Save jkohlin/10d07b786d3624df9560bb23a1d8f151 to your computer and use it in GitHub Desktop.
Filter out keys and or values in an object
/**
* Description
* @param {Object} obj
* @param {function} keyFilter
* @param {function} valueFilter
* @returns {Object}
*/
const objectFilter = (obj, keyFilter, valueFilter) => {
let array = Object.entries(obj) // [ [key, value], [key, value] ]
if (typeof keyFilter === 'function') {
array = array.filter(keyFilter) // keyFilter([key, value]) => key === 'someKey'
}
if (typeof valueFilter === 'function') {
array = array.filter(valueFilter) // valueFilter([key, value]) => value === 'someValue'
}
return array.reduce((acc, [k, v]) => ({ ...acc, [k.split('.')[0]]: v }), {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment