decamelize-keys-deep
Version:
Deeply convert the camelized keys of an object into a lowercased one with a custom separator: unicornRainbow → unicorn_rainbow
32 lines (30 loc) • 988 B
JavaScript
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, options);
});
}
// 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, options)];
});
}
// Something else like a String or Number.
return obj;
}