Last active
March 5, 2018 08:56
-
-
Save tonkla/f040d3d95c2f7379ae6c7cfb09eb8a35 to your computer and use it in GitHub Desktop.
ES6 module to recursively convert between `snake_case` and `camelCase` keys in an object using `lodash`.
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
// Credit: https://gist.github.com/felixjung/a00879103892af44524f | |
// Credit: https://gist.github.com/emcmanus/eb735299788c820b4eb85c38f02598e4 | |
import { | |
camelCase, | |
cloneDeep, | |
isArray, | |
isPlainObject, | |
map, | |
mapKeys, | |
mapValues, | |
snakeCase, | |
} from 'lodash' | |
export function keysToSnakeCase(object) { | |
let snakeCaseObject = cloneDeep(object) | |
if (isArray(snakeCaseObject)) { | |
return map(snakeCaseObject, keysToSnakeCase) | |
} else if (!isPlainObject(snakeCaseObject)) { | |
return snakeCaseObject | |
} | |
snakeCaseObject = mapKeys(snakeCaseObject, (value, key) => { | |
if (key[0] === '_') return key | |
return snakeCase(key) | |
}) | |
return mapValues( | |
snakeCaseObject, | |
(value) => { | |
if (isPlainObject(value)) { | |
return keysToSnakeCase(value) | |
} else if (isArray(value)) { | |
return map(value, keysToSnakeCase) | |
} | |
return value | |
} | |
) | |
} | |
export function keysToCamelCase(object) { | |
let camelCaseObject = cloneDeep(object) | |
if (isArray(camelCaseObject)) { | |
return map(camelCaseObject, keysToCamelCase) | |
} else if (!isPlainObject(camelCaseObject)) { | |
return camelCaseObject | |
} | |
camelCaseObject = mapKeys(camelCaseObject, (value, key) => { | |
if (key[0] === '_') return key | |
return camelCase(key) | |
}) | |
return mapValues( | |
camelCaseObject, | |
(value) => { | |
if (isPlainObject(value)) { | |
return keysToCamelCase(value) | |
} else if (isArray(value)) { | |
return map(value, keysToCamelCase) | |
} | |
return value | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment