Skip to content

Instantly share code, notes, and snippets.

@ntd251
Last active January 10, 2023 09:55
Show Gist options
  • Save ntd251/2bfe6c92df3c4afe772914c7c2f30bed to your computer and use it in GitHub Desktop.
Save ntd251/2bfe6c92df3c4afe772914c7c2f30bed to your computer and use it in GitHub Desktop.
Convert JSON snake-case (underscore) keys to camel-case keys
/**
* @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