Skip to content

Instantly share code, notes, and snippets.

@swashcap
Created November 10, 2015 22:41
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 swashcap/8a4d1338302854566c29 to your computer and use it in GitHub Desktop.
Save swashcap/8a4d1338302854566c29 to your computer and use it in GitHub Desktop.
Get arbitrarily deeply nested objects with a comparator.
/**
* Get deeply nested objects using a 'compare' function.
*
* @param {(object|array)} target Data tree in which to find objects.
* @param {function} compare Passed items in the `target` data tree. It
* should return a boolean value based on the
* item.
* @return {array}
*/
function getDeepObjects(target, compare) {
var found = [];
if (Array.isArray(target)) {
target.forEach(function(childTarget) {
[].push.apply(found, findDeep(childTarget, compare));
});
} else if (target instanceof Object) {
if (compare(target)) {
found.push(target);
} else {
Object.keys(target).forEach(function(key) {
[].push.apply(found, findDeep(target[key], compare));
});
}
}
return found;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment