Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Created March 14, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonewebdesign/09afc4768905a01cf617f98f731c17b5 to your computer and use it in GitHub Desktop.
Save simonewebdesign/09afc4768905a01cf617f98f731c17b5 to your computer and use it in GitHub Desktop.
JSON API: Camelize keys in the client (JavaScript) - functional style
// 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