Skip to content

Instantly share code, notes, and snippets.

@onexdrk
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onexdrk/0b0b84fe6f0c8f0a895b to your computer and use it in GitHub Desktop.
Save onexdrk/0b0b84fe6f0c8f0a895b to your computer and use it in GitHub Desktop.
underscore.js mixin for pick nested properties
/**
* Require _.deep.js from https://gist.github.com/furf/3208381
*/
_.mixin({
deepPick: function (obj) {
var ArrayProto = Array.prototype;
var copy = {};
var keys = ArrayProto.concat.apply(ArrayProto, ArrayProto.slice.call(arguments, 1));
_.each(keys, function(key) {
var val = _.deep(obj, key);
if (!_.isUndefined(val)) _.deep(copy, key, val);
});
return copy;
}
});
//Usage:
// var obj = {
// a : {
// b : 'b',
// c:'c'
// },
// x:{
// y:'y',
// z:'z'
// }
// };
//
//_.deepPick(z, 'a.b','x.z');
//
// result:
// {
// a: {
// b:'b'
// },
// x: {
// z:'z'
// }
//}
@JarnoLeConte
Copy link

I think it needs a small modification, because some Falsy values will be not included. For example:

_.deepPick({count: 0}, ['count'])
=> {}

Solve this problem by changing line 13 to:

if (!_.isUndefined(val)) _.deep(copy, key, val);

Now the example again:

_.deepPick({count: 0}, ['count'])
=> {count: 0}

@onexdrk
Copy link
Author

onexdrk commented Oct 16, 2014

Really, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment