-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (46 loc) · 1.18 KB
/
index.js
File metadata and controls
57 lines (46 loc) · 1.18 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module.exports = prop;
function prop(obj, path, value) {
if (!obj) return undefined;
var isGet = arguments.length === 2;
var parts = path;
if (typeof path === "string") {
if (path.charAt(0) === "/") {
// support /a/b/c
parts = path.substr(1).split("/");
} else {
//support a.b.c.
parts = path.split(".");
}
}
var origParts = JSON.parse(JSON.stringify(parts));
parts = parts.reverse();
var target = obj;
var key = parts.pop();
while (parts.length) {
var nextTarget = target[key];
if (!nextTarget) {
if (value === undefined) {
return undefined;
} else {
nextTarget = target[key] = {};
}
}
if (key == "__proto__" || key == "prototype" || key == "constructor")
return undefined;
target = nextTarget;
key = parts.pop();
}
if (isGet) {
return target[key];
}
if (value !== undefined) {
target[key] = value;
return value;
}
delete target[key];
if (Object.keys(target).length === 0 && origParts.length > 1) {
// Since the case of recursive delete is infrequent, this is likely performant enough.
origParts.pop();
prop(obj, origParts, undefined);
}
}