index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*!
  2. * set-value <https://github.com/jonschlinkert/set-value>
  3. *
  4. * Copyright (c) 2014-2015, 2017, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. var split = require('split-string');
  9. var extend = require('extend-shallow');
  10. var isPlainObject = require('is-plain-object');
  11. var isObject = require('is-extendable');
  12. module.exports = function(obj, prop, val) {
  13. if (!isObject(obj)) {
  14. return obj;
  15. }
  16. if (Array.isArray(prop)) {
  17. prop = [].concat.apply([], prop).join('.');
  18. }
  19. if (typeof prop !== 'string') {
  20. return obj;
  21. }
  22. var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey);
  23. var len = keys.length;
  24. var idx = -1;
  25. var current = obj;
  26. while (++idx < len) {
  27. var key = keys[idx];
  28. if (idx !== len - 1) {
  29. if (!isObject(current[key])) {
  30. current[key] = {};
  31. }
  32. current = current[key];
  33. continue;
  34. }
  35. if (isPlainObject(current[key]) && isPlainObject(val)) {
  36. current[key] = extend({}, current[key], val);
  37. } else {
  38. current[key] = val;
  39. }
  40. }
  41. return obj;
  42. };
  43. function isValidKey(key) {
  44. return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
  45. }