set.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var isIndex = require('../internal/isIndex'),
  2. isKey = require('../internal/isKey'),
  3. isObject = require('../lang/isObject'),
  4. toPath = require('../internal/toPath');
  5. /**
  6. * Sets the property value of `path` on `object`. If a portion of `path`
  7. * does not exist it's created.
  8. *
  9. * @static
  10. * @memberOf _
  11. * @category Object
  12. * @param {Object} object The object to augment.
  13. * @param {Array|string} path The path of the property to set.
  14. * @param {*} value The value to set.
  15. * @returns {Object} Returns `object`.
  16. * @example
  17. *
  18. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  19. *
  20. * _.set(object, 'a[0].b.c', 4);
  21. * console.log(object.a[0].b.c);
  22. * // => 4
  23. *
  24. * _.set(object, 'x[0].y.z', 5);
  25. * console.log(object.x[0].y.z);
  26. * // => 5
  27. */
  28. function set(object, path, value) {
  29. if (object == null) {
  30. return object;
  31. }
  32. var pathKey = (path + '');
  33. path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
  34. var index = -1,
  35. length = path.length,
  36. lastIndex = length - 1,
  37. nested = object;
  38. while (nested != null && ++index < length) {
  39. var key = path[index];
  40. if (isObject(nested)) {
  41. if (index == lastIndex) {
  42. nested[key] = value;
  43. } else if (nested[key] == null) {
  44. nested[key] = isIndex(path[index + 1]) ? [] : {};
  45. }
  46. }
  47. nested = nested[key];
  48. }
  49. return object;
  50. }
  51. module.exports = set;