Last active
February 28, 2017 17:59
-
-
Save elado/4b3b63a6634147041ef83d9b9c5974d3 to your computer and use it in GitHub Desktop.
CaseChange (object deep camelizer/underscorer)
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
import _ from 'lodash' | |
const CaseChange = { | |
camelizeKey: _.memoize(_.camelCase), | |
underscoreKey: _.memoize(_.snakeCase), | |
convertToCamelcase(object) { | |
return deepMapKeys(object, CaseChange.camelizeKey) | |
}, | |
convertToUnderscore(object) { | |
return deepMapKeys(object, CaseChange.underscoreKey) | |
}, | |
camelizeKeysInPlace(object) { | |
deepMutateMapKeys(object, CaseChange.camelizeKey) | |
}, | |
underscoreKeysInPlace(object) { | |
deepMutateMapKeys(object, CaseChange.underscoreKey) | |
} | |
} | |
function deepMapKeys(obj, keyMapper) { | |
if (_.isArray(obj)) { | |
return obj.map(v => deepMapKeys(v, keyMapper)) | |
} | |
else if (_.isObject(obj)) { | |
return _.transform(obj, (a, v, k) => { a[keyMapper(k)] = deepMapKeys(v, keyMapper) }, {}) | |
} | |
else { | |
return obj | |
} | |
} | |
function deepMutateMapKeys(object, fn) { | |
if (_.isArray(object)) { | |
return object.map((item) => deepMutateMapKeys(item, fn)) | |
} | |
else if (_.isObject(object)) { | |
Object.keys(object).forEach((key) => { | |
const value = object[key] | |
delete object[key] | |
object[fn(key)] = deepMutateMapKeys(value, fn) | |
}) | |
} | |
return object | |
} | |
export default ChanceCase |
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
const underscoredObj = { | |
article_id: '1', | |
body: 'hello', | |
comments: [ | |
{ user_id: 'u1', body: 'wow' }, | |
{ user_id: 'u2', body: 'wow' } | |
], | |
author: { | |
user_id: 'u1', | |
avatar_image: { | |
url: 'http://x', | |
size: 'large' | |
} | |
} | |
} | |
const camelizedObj = { | |
articleId: '1', | |
body: 'hello', | |
comments: [ | |
{ userId: 'u1', body: 'wow' }, | |
{ userId: 'u2', body: 'wow' } | |
], | |
author: { | |
userId: 'u1', | |
avatarImage: { | |
url: 'http://x', | |
size: 'large' | |
} | |
} | |
} | |
console.log(CaseChange.convertToCamelcase(underscoredObj)) | |
console.log(CaseChange.convertToUnderscore(camelizedObj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment