/
ObjectPath.ts
37 lines (36 loc) · 898 Bytes
/
ObjectPath.ts
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
export default class ObjectPath {
static get(path: string[], obj, create = false) {
if (!obj) return;
let currObj = obj;
for (const currentPath of path) {
if (currentPath in currObj) {
currObj = currObj[currentPath];
} else if (create) {
currObj[currentPath] = Object.create({});
currObj = currObj[currentPath];
} else {
return;
}
}
return currObj;
}
static set(path: string[], value, obj) {
if (!obj) return;
if (path.length === 0) {
for (const key in obj) {
delete obj[key];
}
for (const key in value) {
obj[key] = value[key];
}
return;
}
const prePath = path.slice();
const lastPath = prePath.pop();
const get = ObjectPath.get(prePath, obj, true);
if (typeof get === "object") {
get[lastPath] = value;
}
return value;
}
}