forked from 418sec/deep-get-set
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
34 lines (30 loc) · 839 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var hasOwnProp = Object.prototype.hasOwnProperty;
module.exports = deep;
function deep(obj, path, value) {
if (arguments.length === 3) return set.apply(null, arguments);
return get.apply(null, arguments);
}
function get(obj, path) {
var keys = Array.isArray(path) ? path : path.split(".");
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!obj || !hasOwnProp.call(obj, key)) {
obj = undefined;
break;
}
obj = obj[key];
}
return obj;
}
function set(obj, path, value) {
obj = Object.create(obj)
value = Object.freeze(value)
var keys = Array.isArray(path) ? path : path.split(".");
for (var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (deep.p && !hasOwnProp.call(obj, key)) obj[key] = {};
obj = obj[key];
}
obj[keys[i]] = value;
return value;
}