Created
October 8, 2015 09:27
-
-
Save incik/4ba210539768371e7b26 to your computer and use it in GitHub Desktop.
Transform camelCase keys of an object into snake_case
This file contains hidden or 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