Created
March 14, 2018 16:30
-
-
Save simonewebdesign/09afc4768905a01cf617f98f731c17b5 to your computer and use it in GitHub Desktop.
JSON API: Camelize keys in the client (JavaScript) - functional style
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
// Converts 'foo-bar' to 'fooBar' | |
// Credits: https://stackoverflow.com/a/6661012 | |
export function camelize(str) { | |
return str.replace(/-([a-z])/g, g => g[1].toUpperCase()); | |
} | |
function camelizeKeys(obj) { | |
return Object.assign(...Object.entries(obj).map( | |
([key, val]) => ({ [camelize(key)]: val }) | |
)); | |
} | |
export function camelizeAttributes(response) { | |
const { data } = response.data; | |
if (!data) return response; | |
return { | |
...response, | |
data: { | |
...response.data, | |
data: Array.isArray(data) | |
? data.map(item => ({ ...item, attributes: camelizeKeys(item.attributes) })) | |
: { ...data, attributes: camelizeKeys(data.attributes) }, | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment