Skip to content

Instantly share code, notes, and snippets.

@weeksie
Created March 13, 2019 16:19
Show Gist options
  • Save weeksie/7eb8e580d1588b0c571e2abeb1edbac5 to your computer and use it in GitHub Desktop.
Save weeksie/7eb8e580d1588b0c571e2abeb1edbac5 to your computer and use it in GitHub Desktop.
Transforming object keys
import { isPlainObject, isArray, camelCase, snakeCase } from 'lodash';
export function snakeKeys(object) {
return deepTransformKeys(object, snakeCase);
}
export function camelKeys(object) {
return deepTransformKeys(object, camelCase);
}
function deepTransformKeys(object, transformer) {
if (!isPlainObject(object)) {
return object;
}
return Object.entries(object).reduce(mapValue, {});
function mapValue(obj, [k, v]) {
obj[transformer(k)] = toValue(v);
return obj;
}
function toValue(v) {
if (isArray(v)) {
return v.map(toValue);
} else if (isPlainObject(v)) {
return deepTransformKeys(v, transformer);
}
return v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment