Created
November 10, 2015 22:41
-
-
Save swashcap/8a4d1338302854566c29 to your computer and use it in GitHub Desktop.
Get arbitrarily deeply nested objects with a comparator.
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
/** | |
* 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