assign.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var assignValue = require('./_assignValue'),
  2. copyObject = require('./_copyObject'),
  3. createAssigner = require('./_createAssigner'),
  4. isArrayLike = require('./isArrayLike'),
  5. isPrototype = require('./_isPrototype'),
  6. keys = require('./keys');
  7. /** Used for built-in method references. */
  8. var objectProto = Object.prototype;
  9. /** Used to check objects for own properties. */
  10. var hasOwnProperty = objectProto.hasOwnProperty;
  11. /**
  12. * Assigns own enumerable string keyed properties of source objects to the
  13. * destination object. Source objects are applied from left to right.
  14. * Subsequent sources overwrite property assignments of previous sources.
  15. *
  16. * **Note:** This method mutates `object` and is loosely based on
  17. * [`Object.assign`](https://mdn.io/Object/assign).
  18. *
  19. * @static
  20. * @memberOf _
  21. * @since 0.10.0
  22. * @category Object
  23. * @param {Object} object The destination object.
  24. * @param {...Object} [sources] The source objects.
  25. * @returns {Object} Returns `object`.
  26. * @see _.assignIn
  27. * @example
  28. *
  29. * function Foo() {
  30. * this.a = 1;
  31. * }
  32. *
  33. * function Bar() {
  34. * this.c = 3;
  35. * }
  36. *
  37. * Foo.prototype.b = 2;
  38. * Bar.prototype.d = 4;
  39. *
  40. * _.assign({ 'a': 0 }, new Foo, new Bar);
  41. * // => { 'a': 1, 'c': 3 }
  42. */
  43. var assign = createAssigner(function(object, source) {
  44. if (isPrototype(source) || isArrayLike(source)) {
  45. copyObject(source, keys(source), object);
  46. return;
  47. }
  48. for (var key in source) {
  49. if (hasOwnProperty.call(source, key)) {
  50. assignValue(object, key, source[key]);
  51. }
  52. }
  53. });
  54. module.exports = assign;