Last active
April 19, 2016 07:07
-
-
Save Sneagan/8366247 to your computer and use it in GitHub Desktop.
Javascript function to recursively convert all keys in a Javascript object from underscore_naming to camelCase. This includes nested objects and objects within nested arrays.
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
var ConvertKeysToCamelCase = function(item_to_convert) { | |
var stringToCamelCase = function(string_to_convert) { | |
return string_to_convert.replace(/-([a-z])/g, function (g) {return g[1].toUpperCase();}); | |
}; | |
var convertKey = function(key_to_convert, key_to_replace) { | |
if (key_to_convert.indexOf('_') != -1) { | |
key_to_convert = key_to_convert.replace(/_/g,'-'); | |
key_to_convert = stringToCamelCase(key_to_convert); | |
item_to_convert[key_to_convert] = item_to_convert[key_to_replace]; | |
delete item_to_convert[key_to_replace]; | |
} | |
} | |
var i = 0; | |
for (var key in item_to_convert) { | |
if (typeof item_to_convert[key] != 'undefined') { | |
if (typeof item_to_convert[key] === 'object' && !(item_to_convert[key] instanceof Array)) { | |
self.ConvertKeysToCamelCase(item_to_convert[key]); | |
} | |
if (item_to_convert[key] instanceof Array) { | |
for (var i = 0; i < item_to_convert[key].length; i++) { | |
self.ConvertKeysToCamelCase(item_to_convert[key][i]); | |
} | |
} | |
var temp_string = key; | |
convertKey(temp_string, key); | |
} | |
i = ++i; | |
} | |
return item_to_convert; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment