Skip to content

Instantly share code, notes, and snippets.

@yurifrl
Last active May 6, 2024 20:11
Show Gist options
  • Save yurifrl/7061e440afea1c01e8d3f421832cb508 to your computer and use it in GitHub Desktop.
Save yurifrl/7061e440afea1c01e8d3f421832cb508 to your computer and use it in GitHub Desktop.
ramda, convert properties of objet into snakeCase or camelCase
import { concat, zipObj, keys, values, map, isEmpty, curry } from 'ramda'
const log = curry(console.log)
const snakeCaseObj = [{
a_b: "asdasdasd",
c_a: "2018-02-20T18:43:17.104Z",
t_c: {
s_d: "2018-02-20",
e_d: "2018-02-20",
b_t: {
c_a: "2018-02-20T18:43:17.104Z"
}
},
v_b: {
g_a: "2018-02-20T18:43:17.104Z"
}
}]
const camelCaseObj = [{
aB: "asdasdasd",
cA: "2018-02-20T18:43:17.104Z",
tC: {
sD: "2018-02-20",
eD: "2018-02-20",
bT: {
cA: "2018-02-20T18:43:17.104Z"
}
},
vB: {
gA: "2018-02-20T18:43:17.104Z"
}
}]
const camelCase = str => str.replace(/[-_]([a-z])/g, m => m[1].toUpperCase())
const snakeCase = str => str.replace(/([A-Z])/g, x => concat('_', x.toLowerCase()))
const parseValues = curry((fn, obj) => {
if(isEmpty(keys(obj))) {
return obj
} else {
return mapKeys(fn, obj)
}
})
const mapKeys = curry((fn, obj) => zipObj(map(fn, keys(obj)), map(parseValues(fn), values(obj))));
const fold = curry((fn, value) => is(Array, value) ? map(fn, value) : fn(value))
const toCamelCase = fold(mapKeys(camelCase), __)
const toSnakeCase = fold(mapKeys(snakeCase), __)
toSnakeCase(camelCaseObj)
toCamelCase(snakeCaseObj)
@MikeDabrowski
Copy link

Wont work with arrays in values s_d: ['2018-02-20'],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment