Created
October 23, 2015 10:04
-
-
Save felixjung/a00879103892af44524f to your computer and use it in GitHub Desktop.
ES6 module to recursively convert snake case keys in an object to camel case using lodash.
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
'use strict'; | |
import 'lodash'; | |
export default function (object) { | |
let camelCaseObject = _.cloneDeep(object); | |
// Convert keys to camel case | |
camelCaseObject = _.mapKeys(camelCaseObject, (value, key) => { | |
return key.replace(/(_\w)/, match => match[1].toUpperCase()); | |
}); | |
// Recursively apply throughout object | |
return _.mapValues( | |
camelCaseObject, | |
value => { | |
if (_.isPlainObject(value)) { | |
return keysToCamelCase(value); | |
} else if (_.isArray(value)) { | |
return _.map(value, keysToCamelCase); | |
} else { | |
return value; | |
} | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Use global replace for multiple snake_case words (e.g.
my_bad_key
).https://gist.github.com/emcmanus/eb735299788c820b4eb85c38f02598e4/revisions