_baseSet.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import assignValue from './_assignValue.js';
  2. import castPath from './_castPath.js';
  3. import isIndex from './_isIndex.js';
  4. import isObject from './isObject.js';
  5. import toKey from './_toKey.js';
  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. export default baseSet;