Skip to content

Instantly share code, notes, and snippets.

@eliranmal
Created October 30, 2014 13:49
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 eliranmal/f9ccf84ce8d80ef57a0f to your computer and use it in GitHub Desktop.
Save eliranmal/f9ccf84ce8d80ef57a0f to your computer and use it in GitHub Desktop.
function fn(obj, key) {
if (_.has(obj, key)) // or just (key in obj)
return [obj];
// elegant:
return _.flatten(_.map(obj, function(v) {
return typeof v == "object" ? fn(v, key) : [];
}), true);
// or efficient:
var res = [];
_.forEach(obj, function(v) {
if (typeof v == "object" && (v = fn(v, key)).length)
res.push.apply(res, v);
});
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment