-
-
Save poteirard/fca4b7ac8da6f1f100e6fbdc5c48d7f8 to your computer and use it in GitHub Desktop.
Transform camelCase keys of an object into snake_case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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