Skip to content

Instantly share code, notes, and snippets.

@EmilyRosina
Last active October 29, 2018 20:18
Show Gist options
  • Save EmilyRosina/9ccc0c0bac9ae7d5138c2f64ddcd51cd to your computer and use it in GitHub Desktop.
Save EmilyRosina/9ccc0c0bac9ae7d5138c2f64ddcd51cd to your computer and use it in GitHub Desktop.
Vue plugin to add helpers that transform obj from snake_cased keys to camelCased keys and back again.
import _ from 'lodash'
const transform = {
toCamelCase (obj) {
const camelCasedObj = {}
Object.keys(obj).forEach((key) => {
if (_.isPlainObject(obj[key])) camelCasedObj[_.camelCase(key)] = this.toCamelCase(obj[key])
else camelCasedObj[_.camelCase(key)] = obj[key]
})
return camelCasedObj
},
toSnakeCase (obj) {
const snakeCasedObj = {}
Object.keys(obj).forEach((key) => {
if (_.isPlainObject(obj[key])) snakeCasedObj[_.snakeCase(key)] = this.toSnakeCase(obj[key])
else snakeCasedObj[_.snakeCase(key)] = obj[key]
})
return snakeCasedObj
}
}
/**
* Adds .$transform helper to Vue instance.
* - This helper transforms case of all object keys, depending upon method called
* - Created to erradicate the need to hush eslint, where API returns snake_cased keys on objects
* @param [Object] must be a js object
* @returns Object with renamed keys (recursive)
* @example
* this.$transform.toCamelCase({ some_key: 123 })
* => { someKey: 123 }
* @example
* this.$transform.toSnakeCase({ someKey: 123 })
* => { some_key: 123 }
*/
const transformPlugin = {
install (Vue, options) {
Vue.prototype.$transform = transform
}
}
export default transformPlugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment