Skip to content

Instantly share code, notes, and snippets.

@bernardoadc
Last active August 21, 2021 06:23
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 bernardoadc/872d5a174108823159d845cc5baba337 to your computer and use it in GitHub Desktop.
Save bernardoadc/872d5a174108823159d845cc5baba337 to your computer and use it in GitHub Desktop.
Vanilla filter for objects, with several filter types accepted
function objFilter (obj, filter, nonstrict) {
const r = {}
if (!filter) return r
if (typeof filter == 'string') return {[filter]: obj[filter]}
for (const p in obj) {
if (typeof filter == 'object' && nonstrict && obj[p] == filter[p]) r[p] = obj[p]
else if (typeof filter == 'object' && !nonstrict && obj[p] === filter[p]) r[p] = obj[p]
else if (typeof filter == 'function') if (filter(obj[p], p, obj)) r[p] = obj[p]
else if (filter.length && filter.includes(p)) r[p] = obj[p]
}
return r
}
function filter(o,f,ns){if(r={},!f)return{};if("string"==typeof f)return{[f]:o[f]};for(p in o)"object"==typeof f&&ns&&o[p]==f[p]?r[p]=o[p]:"object"!=typeof f||ns||o[p]!==f[p]?"function"==typeof f?f(o[p],p,o)&&(r[p]=o[p]):f.length&&f.includes(p)&&(r[p]=o[p]):r[p]=o[p];return r}
@bernardoadc
Copy link
Author

Usage by examples:

obj = {a:1, b:2, c:3}
objFilter(obj, 'a') // returns: {a: 1}
objFilter(obj, ['a','b']) // returns: {a: 1, b: 2}
objFilter(obj, {a:1}) // returns: {a: 1}
objFilter(obj, {'a':'1'}, true) // returns: {a: 1}
objFilter(obj, (v,k,o) => v%2===1) // returns: {a: 1, c: 3}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment