-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransformObj.js
More file actions
113 lines (102 loc) · 2.74 KB
/
Copy pathtransformObj.js
File metadata and controls
113 lines (102 loc) · 2.74 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//*****V1;
const transformObj = (obj, cb) => {
const loopObj = (obj, newObj = {}) => {
for (const key in obj) {
if (typeof obj[key] === "object" && !Array.isArray(obj[key])) {
// stage object keys
if (!newObj[key]) newObj[key] = {};
// recurse through inner keys
loopObj(obj[key], newObj[key]);
}
if (!newObj[key]) {
cb(newObj, obj, key);
}
}
return newObj;
};
return loopObj(obj);
};
const transformer = (newObj, oldObj, key) => {
newObj[key] = oldObj[key];
};
// Example 1
const obj1 = {
a: {
ab: [{name: "vic", age: 20}],
ac: [{name: "nancy", age: 18}],
ad: {
adb: [{name: "vic", age: 30}]
},
av: {
adv: [{name: "vic", age: 30}],
ade: {
adf: [{name: "vic", age: 30}]
}
}
},
b: {
bb: [{name: "vic", age: 20}],
bc: [{name: "nancy", age: 18}],
bd: {
be: [{name: "nancy", age: 18}]
}
},
c: "123"
};
v = transformObj(obj1, transformer);
// An Example of Transforming Keys Deeply Nested
const addVicToKeys = (newObj, oldObj, key) => {
newObj[key] = oldObj[key] + " Vic";
};
const testObj = {
a: 1,
b: {
c: 3,
d: {
e: 4,
f: {
g: 5,
h: {
i: 6,
j: {k: 7}
}
}
}
}
};
const result = transformObj(testObj, addVicToKeys);
console.log(util.inspect(result, {showHidden: false, depth: null, colors: true}));
// const isSame = JSON.stringify(v) === JSON.stringify(obj);
// console.log(isSame);
//***V2 - BEST
// Transform Object V2 using modern ES6 Javascript methods
const transformObjV2 = (origObj, cb) => Object.keys(origObj)
.reduce((newObj, key) => {
if (typeof origObj[key] === "object" && !Array.isArray(origObj[key])) {
return {...newObj, [key]: transformObjV2(origObj[key], cb)};
}
if (!newObj[key]) {
cb(newObj, origObj, key);
}
return newObj;
}, {});
const sampleTransformer = (newObj, origObj, key) => {
const currentValue = origObj[key];
if (Array.isArray(currentValue)) {
newObj[key] = [3, 4, 5];
} else if (currentValue === "vic") {
newObj[key] = "victor";
} else {
newObj[key] = currentValue + "vic";
}
};
const sampleObj = {
a: 1,
b: 2,
c: {
d: 3,
e: [1, 2, 3]
},
f: "vic"
};
transformObjV2(sampleObj, sampleTransformer);