Skip to content

Instantly share code, notes, and snippets.

@modulsx
Last active February 19, 2021 09:12
Show Gist options
  • Save modulsx/1198c4db330886c854235b4f142445f5 to your computer and use it in GitHub Desktop.
Save modulsx/1198c4db330886c854235b4f142445f5 to your computer and use it in GitHub Desktop.
Convert Object Keys To Different String Cases (ex: camelCase And snake_case)
const { transform, set } = require('lodash');
const {
isArray, isObjectLike, isPlainObject, map,
} = require('lodash/fp')
const { camelCase, snakeCase } = require('lodash');
function createIteratee(converter, self) {
return (result, value, key) => set(result, converter(key), isObjectLike(value) ? self(value) : value)
}
function createHumps(keyConverter) {
return function humps(node) {
if (isArray(node)) return map(humps, node)
if (isPlainObject(node)) return transform(node, createIteratee(keyConverter, humps))
return node
}
}
function objectKeyCaseDeepTransform(toCase, obj) {
const humps = createHumps(toCase)
return humps(obj)
}
// Test 1
const object1 = { attrOne: 'foo', attrTwo: 'bar', attrThree: { attrOne: 'foo' } }
console.log(objectKeyCaseDeepTransform(snakeCase, object1))
// Test 2
const object2 = { attr_one: 'foo', attr_two: 'bar', attr_three: { attr_one: 'foo' } }
console.log(objectKeyCaseDeepTransform(camelCase, object2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment