forked from rxaviers/decamelize-keys-deep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
31 lines (30 loc) · 970 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
var decamelize = require("decamelize");
var mapObj = require("map-obj");
module.exports = function decamelizeKeysDeep(obj, options) {
// Any falsy, which includes `null` whose typeof is `object`.
if (!obj) {
return obj;
}
// Date, whose typeof is `object` too.
if (obj instanceof Date) {
return obj;
}
// Array, whose typeof is `object` too.
if (Array.isArray(obj)) {
return obj.map(function(element) {
return decamelizeKeysDeep(element);
});
}
// So, if this is still an `object`, we might be interested in it.
if (typeof obj === "object") {
return mapObj(obj, function(key, value) {
var newKey = decamelize(key, options);
if (key !== newKey && newKey in obj) {
throw new Error("Decamelized key `" + newKey + "` would overwrite existing key of the given JSON object");
}
return [newKey, decamelizeKeysDeep(value)];
});
}
// Something else like a String or Number.
return obj;
}