You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.2 KiB

4 years ago
  1. var assignValue = require('./_assignValue'),
  2. castPath = require('./_castPath'),
  3. isIndex = require('./_isIndex'),
  4. isObject = require('./isObject'),
  5. toKey = require('./_toKey');
  6. /**
  7. * The base implementation of `_.set`.
  8. *
  9. * @private
  10. * @param {Object} object The object to modify.
  11. * @param {Array|string} path The path of the property to set.
  12. * @param {*} value The value to set.
  13. * @param {Function} [customizer] The function to customize path creation.
  14. * @returns {Object} Returns `object`.
  15. */
  16. function baseSet(object, path, value, customizer) {
  17. if (!isObject(object)) {
  18. return object;
  19. }
  20. path = castPath(path, object);
  21. var index = -1,
  22. length = path.length,
  23. lastIndex = length - 1,
  24. nested = object;
  25. while (nested != null && ++index < length) {
  26. var key = toKey(path[index]),
  27. newValue = value;
  28. if (index != lastIndex) {
  29. var objValue = nested[key];
  30. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  31. if (newValue === undefined) {
  32. newValue = isObject(objValue)
  33. ? objValue
  34. : (isIndex(path[index + 1]) ? [] : {});
  35. }
  36. }
  37. assignValue(nested, key, newValue);
  38. nested = nested[key];
  39. }
  40. return object;
  41. }
  42. module.exports = baseSet;