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
|
|
8
|
'use strict';
|
9
|
|
10
|
var split = require('split-string');
|
11
|
var extend = require('extend-shallow');
|
12
|
var isPlainObject = require('is-plain-object');
|
13
|
var isObject = require('is-extendable');
|
14
|
|
15
|
module.exports = function(obj, prop, val) {
|
16
|
if (!isObject(obj)) {
|
17
|
return obj;
|
18
|
}
|
19
|
|
20
|
if (Array.isArray(prop)) {
|
21
|
prop = [].concat.apply([], prop).join('.');
|
22
|
}
|
23
|
|
24
|
if (typeof prop !== 'string') {
|
25
|
return obj;
|
26
|
}
|
27
|
|
28
|
var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey);
|
29
|
var len = keys.length;
|
30
|
var idx = -1;
|
31
|
var current = obj;
|
32
|
|
33
|
while (++idx < len) {
|
34
|
var key = keys[idx];
|
35
|
if (idx !== len - 1) {
|
36
|
if (!isObject(current[key])) {
|
37
|
current[key] = {};
|
38
|
}
|
39
|
current = current[key];
|
40
|
continue;
|
41
|
}
|
42
|
|
43
|
if (isPlainObject(current[key]) && isPlainObject(val)) {
|
44
|
current[key] = extend({}, current[key], val);
|
45
|
} else {
|
46
|
current[key] = val;
|
47
|
}
|
48
|
}
|
49
|
|
50
|
return obj;
|
51
|
};
|
52
|
|
53
|
function isValidKey(key) {
|
54
|
return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
|
55
|
}
|