_baseSet.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  29. return object;
  30. }
  31. if (index != lastIndex) {
  32. var objValue = nested[key];
  33. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  34. if (newValue === undefined) {
  35. newValue = isObject(objValue)
  36. ? objValue
  37. : (isIndex(path[index + 1]) ? [] : {});
  38. }
  39. }
  40. assignValue(nested, key, newValue);
  41. nested = nested[key];
  42. }
  43. return object;
  44. }
  45. module.exports = baseSet;