Skip to content

Instantly share code, notes, and snippets.

@poteirard
Forked from incik/snakify.js
Created December 14, 2017 14:24
Show Gist options
  • Save poteirard/fca4b7ac8da6f1f100e6fbdc5c48d7f8 to your computer and use it in GitHub Desktop.
Save poteirard/fca4b7ac8da6f1f100e6fbdc5c48d7f8 to your computer and use it in GitHub Desktop.
Transform camelCase keys of an object into snake_case
function snakifyKeys(fields) {
// because this function can receive map of ArrayNodes, we have to do this
let jsonFields = JSON.parse(JSON.stringify(fields));
for (let key in jsonFields) {
if (jsonFields[key] instanceof Object) {
// we need to go deeper!
jsonFields[key] = snakifyKeys(jsonFields[key]);
}
let snakeKey = key.replace(/\.?([A-Z]+)/g, function(x, y) {return '_' + y.toLowerCase();}).replace(/^_/, '');
jsonFields[snakeKey] = jsonFields[key];
// remove the unwanted camelCase key
if (snakeKey !== key) {
delete jsonFields[key];
}
}
return jsonFields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment