Skip to content

Instantly share code, notes, and snippets.

@felixjung
Created October 23, 2015 10:04
Show Gist options
  • Save felixjung/a00879103892af44524f to your computer and use it in GitHub Desktop.
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.
'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;
}
}
);
}
@emcmanus
Copy link

emcmanus commented Mar 3, 2017

Nice! Use global replace for multiple snake_case words (e.g. my_bad_key).

https://gist.github.com/emcmanus/eb735299788c820b4eb85c38f02598e4/revisions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment