Skip to content

Instantly share code, notes, and snippets.

@nrkn
Created October 3, 2019 01:00
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 nrkn/105987b94fd068e2378cc6aa95006623 to your computer and use it in GitHub Desktop.
Save nrkn/105987b94fd068e2378cc6aa95006623 to your computer and use it in GitHub Desktop.
object filter
export const objectFilter = ( obj, predicate ) => {
if ( obj === null || obj === undefined )
throw Error( 'Cannot convert null or undefined to an object' )
if ( typeof predicate !== 'function' )
throw Error( 'Expected predicate to be a function' )
obj = Object( obj )
return Object.keys( obj ).reduce(
( filtered, key ) => {
if(
Object.prototype.hasOwnProperty.call( obj, key ) &&
predicate( obj[ key ], key, obj )
){
filtered[ key ] = obj[ key ]
}
return filtered
},
{}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment