-
Notifications
You must be signed in to change notification settings - Fork 2
/
ObjUtil.ts
61 lines (56 loc) · 1.78 KB
/
ObjUtil.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* *****************************************************
*/
export class ObjUtil {
public static addAllProps(sourceObj, targetObj): any {
if (null == sourceObj || 'object' !== typeof sourceObj) {
return targetObj;
}
if (null == targetObj || 'object' !== typeof targetObj) {
return targetObj;
}
for (const attr in sourceObj) {
if (sourceObj.hasOwnProperty(attr)) {
targetObj[attr] = sourceObj[attr];
}
}
return targetObj;
}
public static cloneOwnProps(sourceObj): any {
if (null == sourceObj || 'object' !== typeof sourceObj) {
return sourceObj;
}
const copy = sourceObj.constructor();
for (const attr in sourceObj) {
if (sourceObj.hasOwnProperty(attr)) {
copy[attr] = ObjUtil.cloneOwnProps(sourceObj[attr]);
}
}
return copy;
}
public static copyNonNullFieldsOnly(obj, newObj, filterFn?: (prop) => boolean) {
for (const prop in obj) {
if (!filterFn || filterFn(prop)) {
const type = typeof obj[prop];
if (type !== 'function') {
const val = obj[prop];
if (val) {
newObj[prop] = val;
}
}
}
}
return newObj;
}
public static formatRecAttr(o, prettyPrint?: true): string {
// @TODO - add a filter here to build a cache and detect (and skip) circular references
if (prettyPrint) {
return JSON.stringify(o, null, 2);
} else {
return JSON.stringify(o);
}
}
public static newInstance(type) {
return new type();
}
}