pick.js 786 B

123456789101112131415161718192021222324252627282930
  1. var each = require('./each');
  2. var isPlaineObject = require('./type/is-plain-object');
  3. var hasOwnProperty = Object.prototype.hasOwnProperty;
  4. /**
  5. * Creates an object composed of the picked `object` properties.
  6. *
  7. * @param {Object} object The source object.
  8. * @param {...(string|string[])} [paths] The property paths to pick.
  9. * @returns {Object} Returns the new object.
  10. * @example
  11. *
  12. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  13. * pick(object, ['a', 'c']); // => { 'a': 1, 'c': 3 }
  14. */
  15. var pick = function pick(object, keys) {
  16. if (object === null || !isPlaineObject(object)) {
  17. return {};
  18. }
  19. var result = {};
  20. each(keys, function (key) {
  21. if (hasOwnProperty.call(object, key)) {
  22. result[key] = object[key];
  23. }
  24. });
  25. return result;
  26. };
  27. module.exports = pick;