Last active
January 10, 2023 09:55
-
-
Save ntd251/2bfe6c92df3c4afe772914c7c2f30bed to your computer and use it in GitHub Desktop.
Convert JSON snake-case (underscore) keys to camel-case keys
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
/** | |
* @author ntd251 | |
* @dependency underscore.js | |
* @example | |
* | |
* input = { | |
* arrayItems: [ | |
* numericKey: 10, | |
* jsonKey: { | |
* textValue: 'ok' | |
* } | |
* ] | |
* } | |
* | |
* output = { | |
* array_items: [ | |
* numberic_key: 10, | |
* json_key: { | |
* text_value: 'ok' | |
* } | |
* ] | |
* } | |
*/ | |
function snakeToCamel(json) { | |
/** | |
* string, number, null, undefined, boolean, ... | |
*/ | |
if (!json || typeof json !== 'object') { | |
return json; | |
} | |
/** | |
* Array | |
*/ | |
if (json.constructor.name === 'Array') { | |
return json.map((item) => (snakeToCamel(item))); | |
} | |
/** | |
* JSON | |
*/ | |
let output = {}; | |
Object.keys(json).forEach((key) => { | |
let value = json[key]; | |
let newKey = key.includes('_') ? _.string.camelize(key) : key; | |
output[newKey] = snakeToCamel(value); | |
}); | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment