Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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
You can’t perform that action at this time.