Skip to content

Instantly share code, notes, and snippets.

@reu
Created September 23, 2015 14:41
Show Gist options
  • Save reu/86930849b7a2a549bf2f to your computer and use it in GitHub Desktop.
Save reu/86930849b7a2a549bf2f to your computer and use it in GitHub Desktop.
Simple Angular function to convert underline case object keys to camel case
(function(angular) {
function underlineToCamelCase(string) {
return string.replace(/(\_[a-z])/g, function(match) {
return match.toUpperCase().replace("_", "");
});
}
function convertToCamelCaseObject(object) {
if (typeof object != "object") return object;
return Object.keys(object).reduce(function(newObject, key) {
var newKey = underlineToCamelCase(key);
if (object[key] instanceof Array) {
newObject[newKey] = object[key].map(convertToCamelCaseObject);
} else if (object[key] instanceof Object) {
newObject[newKey] = convertToCamelCaseObject(object[key]);
} else {
newObject[newKey] = object[key];
}
return newObject;
}, {});
}
function responseToObject(response) {
if (response.data instanceof Array)
return response.data.map(responseToObject);
return convertToCamelCaseObject(response.data);
}
return angular.module("response-to-object", []).factory("responseToObject", responseToObject);
})(window.angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment