update.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. var baseUpdate = require('./_baseUpdate'),
  2. castFunction = require('./_castFunction');
  3. /**
  4. * This method is like `_.set` except that accepts `updater` to produce the
  5. * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
  6. * is invoked with one argument: (value).
  7. *
  8. * **Note:** This method mutates `object`.
  9. *
  10. * @static
  11. * @memberOf _
  12. * @since 4.6.0
  13. * @category Object
  14. * @param {Object} object The object to modify.
  15. * @param {Array|string} path The path of the property to set.
  16. * @param {Function} updater The function to produce the updated value.
  17. * @returns {Object} Returns `object`.
  18. * @example
  19. *
  20. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  21. *
  22. * _.update(object, 'a[0].b.c', function(n) { return n * n; });
  23. * console.log(object.a[0].b.c);
  24. * // => 9
  25. *
  26. * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
  27. * console.log(object.x[0].y.z);
  28. * // => 0
  29. */
  30. function update(object, path, updater) {
  31. return object == null ? object : baseUpdate(object, path, castFunction(updater));
  32. }
  33. module.exports = update;