Created
March 13, 2019 16:19
-
-
Save weeksie/7eb8e580d1588b0c571e2abeb1edbac5 to your computer and use it in GitHub Desktop.
Transforming object keys
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
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