-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathobject.js
49 lines (47 loc) · 1.04 KB
/
object.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
exports.set = function (target, path, value) {
const fields = path.split('.')
let obj = target
const l = fields.length
for (let i = 0; i < l - 1; i++) {
const key = fields[i]
if (!obj[key]) {
obj[key] = {}
}
obj = obj[key]
}
obj[fields[l - 1]] = value
}
exports.get = function (target, path) {
const fields = path.split('.')
let obj = target
const l = fields.length
for (let i = 0; i < l - 1; i++) {
const key = fields[i]
if (!obj[key]) {
return undefined
}
obj = obj[key]
}
return obj[fields[l - 1]]
}
exports.unset = function (target, path) {
const fields = path.split('.')
let obj = target
const l = fields.length
const objs = []
for (let i = 0; i < l - 1; i++) {
const key = fields[i]
if (!obj[key]) {
return
}
objs.unshift({ parent: obj, key, value: obj[key] })
obj = obj[key]
}
delete obj[fields[l - 1]]
// Clear empty objects
for (const { parent, key, value } of objs) {
if (!Object.keys(value).length) {
delete parent[key]
}
}
}