Created
September 23, 2015 14:41
-
-
Save reu/86930849b7a2a549bf2f to your computer and use it in GitHub Desktop.
Simple Angular function to convert underline case object keys to camel case
This file contains hidden or 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
(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