Last active
November 19, 2018 19:42
-
-
Save ordazgustavo/b2e07a617799355989e13ab8077464fc to your computer and use it in GitHub Desktop.
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
/** | |
* Parses json keys to camel or snake case | |
* Use lodash to convert strings to camelCase or snake-case | |
* | |
* @param {Object} json | |
* @param {Boolean} camel | |
*/ | |
function parseJsonKeys(json = {}, camel = true) { | |
if (typeof json === 'object') { | |
const arr = Object.entries(json) | |
return arr.reduce((acc, [key, val]) => { | |
const camelKey = camel ? _.camelCase(key) : _.snakeCase(key) | |
let value = val | |
if (value instanceof Array) { | |
value = value.map(el => { | |
if (typeof el === 'string') { | |
return el | |
} | |
return parseJsonKeys(el) | |
}) | |
} else if (typeof value === 'object') { | |
value = parseJsonKeys(value) | |
} | |
return { | |
...acc, | |
[camelKey]: value | |
} | |
}, {}) | |
} | |
throw new Error( | |
'First argument should be an Object, received: ' + typeof json | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment