Last active
August 21, 2021 06:23
-
-
Save bernardoadc/872d5a174108823159d845cc5baba337 to your computer and use it in GitHub Desktop.
Vanilla filter for objects, with several filter types accepted
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
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 | |
} |
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
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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage by examples: