Skip to content

Instantly share code, notes, and snippets.

@ordazgustavo
Last active November 19, 2018 19:42
Show Gist options
  • Save ordazgustavo/b2e07a617799355989e13ab8077464fc to your computer and use it in GitHub Desktop.
Save ordazgustavo/b2e07a617799355989e13ab8077464fc to your computer and use it in GitHub Desktop.
/**
* 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