-
-
Save anismiles/51ed047a0fc0a76469bf1a978312c21c to your computer and use it in GitHub Desktop.
ramda, convert properties of objet into snakeCase or camelCase
This file contains hidden or 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 { 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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment