Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vanilla filter for objects, with several filter types accepted
function objFilter(obj, filter, nonstrict){
r = {}
if (!filter) return {}
if (typeof filter == 'string') return {[filter]: obj[filter]}
for (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

This comment has been minimized.

Copy link
Owner Author

@bernardoadc bernardoadc commented Dec 13, 2018

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
You can’t perform that action at this time.