Created
January 31, 2022 19:34
-
-
Save Corky3892/24e6810b4c118e788d235767b0580886 to your computer and use it in GitHub Desktop.
Parse an object recursively, applying a test function to each entry and return true on the first entry which passes the test function.
This file contains hidden or 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
/** | |
* This method will scan the provided object recursively looking for entries which match the test function. When one is found will return true. Sample Usage: | |
* ``` | |
* // Return those objects in the objArray with an entry equal to apple. | |
* objArr.filter(x, (o, k) => o[k] === 'apple'); | |
* ``` | |
* | |
* @param o The object to filter. | |
* @param fn The predicate function to test at each level of the object. | |
* @returns A boolean which when true indicates that the object meets the condition. | |
*/ | |
export function filterDeep<T extends object>(o: T, fn: (obj: T[keyof T], key: keyof T) => boolean): boolean { | |
for (const i in o) { | |
if (fn.apply(this, [o, i, o[i]])) { | |
return true; | |
} | |
if (o[i] !== null && typeof(o[i]) === 'object') { | |
filterObject(<any>o[i], fn); // If anyone feels like tackling this one let me know... | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment