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';
/**
* @example
* import keysToCamelCase from './snakeToCamelCase';
* keysToCamelCase({bad_key: 1}); => {badKey: 1}
* keysToCamelCase([{bad_key: 1}]); => [{badKey: 1}]
*/
function keysToCamelCase(object) {
let camelCaseObject = _.cloneDeep(object);
if (_.isArray(camelCaseObject)) {
return _.map(camelCaseObject, keysToCamelCase);
} else {
camelCaseObject = _.mapKeys(camelCaseObject, (value, key) => {
return _.camelCase(key);
});
// 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;
}
});
}
}
export default keysToCamelCase;
@emcmanus

This comment has been minimized.

Copy link
Owner Author

commented Mar 30, 2017

Latest version handles case where top-level object is an array

Previously [{a:1}] would become {0: {a:1}}

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.