-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (63 loc) · 1.54 KB
/
index.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const decamelize = (object) => {
if (!object) {
return object;
}
const keys = Object.keys(object);
const newKeys = keys.map((key) => {
return key
.replace(/([a-z\d])([A-Z])/g, (match, p1, p2) => {
if (match) {
return `${p1}_${p2}`;
}
})
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, (match, p1, p2) => {
if (match) {
return `${p1}_${p2}`;
}
})
.toLowerCase();
});
return newKeys.reduce((acc, cur, index) => {
const obj = object[keys[index]];
let value = obj;
if (Array.isArray(obj)) {
value = obj.map((item) => {
return typeof item === 'object' ? decamelize(item): item;
});
} else if (typeof obj === 'object') {
value = decamelize(obj);
}
return {
...acc,
[cur]: value,
}
}, {})
}
const camelize = (object) => {
if (!object) {
return object;
}
const keys = Object.keys(object);
const newKeys = keys.map((key) => {
return key.replace(/[_]+(\w)/g, (match, p1) => {
if (match) return p1.toUpperCase();
});
});
return newKeys.reduce((acc, cur, index) => {
const obj = object[keys[index]];
let value = obj;
if (Array.isArray(obj)) {
value = obj.map((item) => {
return typeof item === 'object' ? camelize(item): item;
});
} else if (typeof obj === 'object') {
value = camelize(obj);
}
return {
...acc,
[cur]: value,
}
}, {})
}
module.exports.decamelize = decamelize;
module.exports.camelize = camelize;