pick.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var baseFlatten = require('../internal/baseFlatten'),
  2. bindCallback = require('../internal/bindCallback'),
  3. pickByArray = require('../internal/pickByArray'),
  4. pickByCallback = require('../internal/pickByCallback'),
  5. restParam = require('../function/restParam');
  6. /**
  7. * Creates an object composed of the picked `object` properties. Property
  8. * names may be specified as individual arguments or as arrays of property
  9. * names. If `predicate` is provided it's invoked for each property of `object`
  10. * picking the properties `predicate` returns truthy for. The predicate is
  11. * bound to `thisArg` and invoked with three arguments: (value, key, object).
  12. *
  13. * @static
  14. * @memberOf _
  15. * @category Object
  16. * @param {Object} object The source object.
  17. * @param {Function|...(string|string[])} [predicate] The function invoked per
  18. * iteration or property names to pick, specified as individual property
  19. * names or arrays of property names.
  20. * @param {*} [thisArg] The `this` binding of `predicate`.
  21. * @returns {Object} Returns the new object.
  22. * @example
  23. *
  24. * var object = { 'user': 'fred', 'age': 40 };
  25. *
  26. * _.pick(object, 'user');
  27. * // => { 'user': 'fred' }
  28. *
  29. * _.pick(object, _.isString);
  30. * // => { 'user': 'fred' }
  31. */
  32. var pick = restParam(function(object, props) {
  33. if (object == null) {
  34. return {};
  35. }
  36. return typeof props[0] == 'function'
  37. ? pickByCallback(object, bindCallback(props[0], props[1], 3))
  38. : pickByArray(object, baseFlatten(props));
  39. });
  40. module.exports = pick;