-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
38 lines (32 loc) · 846 Bytes
/
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
const camelCase = require('camelcase');
function properJSONify(obj, keyTransform, customKeySort) {
if (typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
const newArr = [];
var n = obj.length;
while(n--) {
newArr[n] = properJSONify(obj[n], keyTransform);
}
return newArr;
}
const newObject = {};
if (!keyTransform) {
keyTransform = camelCase;
}
const keys = Object.keys(obj).sort(customKeySort).reverse();
var n = keys.length;
while(n--) {
const key = keys[n];
const transformedKey = keyTransform(key);
const value = properJSONify(obj[key], keyTransform);
if (newObject[transformedKey]) {
newObject[`_${transformedKey}`] = value;
} else {
newObject[transformedKey] = value;
}
}
return newObject;
}
module.exports = properJSONify;