Lodash's `pick()` Function

Given an object obj and an array of string paths , Lodash's pick() function returns a new object with just the keys paths from obj .

const obj = { name : 'Will Riker' , rank : 'Commander' , age : 29 }; const picked = _.pick(obj, [ 'name' , 'rank' ]); picked === obj; picked.name; picked.rank; picked.age;

The pick() function also supports dotted paths and any other syntax that Lodash's get() function supports. For example, if name is a nested object with 2 properties, first and last , you can pick just name.last and omit name.first .

const obj = { name : { first : 'Will' , last : 'Riker' }, rank : 'Commander' , age : 29 }; const picked = _.pick(obj, [ 'name.last' , 'rank' ]); picked === obj; picked.name.first; picked.name.last; picked.rank; picked.age;

pick() is permissive when it comes to missing properties. If you try to pick() a dotted property whose parent is undefined, Lodash will just ignore that path.

const obj = { name : 'Will Riker' , rank : 'Commander' , age : 29 }; const picked = _.pick(obj, [ 'name' , 'this.is.not.in.the.object' ]); picked === obj; picked.name; picked.rank; picked.age;

Several other frameworks have analogous pick() functions. For example, Mongoose schemas have a pick() function that creates a new schema a subset of the original schema's paths.

More Lodash Tutorials