Created
August 1, 2012 17:33
-
-
Save chjj/3229094 to your computer and use it in GitHub Desktop.
toUnderscore and toCamel functions
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
function toUnderscore(obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj; | |
} | |
if (Array.isArray(obj)) { | |
return obj.forEach(toUnderscore); | |
} | |
Object.keys(obj).forEach(function (key) { | |
if (/[a-z][A-Z]/.test(key)) { | |
var k = key.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); | |
obj[k] = obj[key]; | |
delete obj[key]; | |
key = k; | |
} | |
toUnderscore(obj[key]); | |
}); | |
return obj; | |
} | |
function toCamel(obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj; | |
} | |
if (Array.isArray(obj)) { | |
return obj.forEach(toCamel); | |
} | |
Object.keys(obj).forEach(function (key) { | |
if (/[a-z]_[a-z]/.test(key)) { | |
var k = key.replace(/([a-z])_([a-z])/g, function (_, $1, $2) { | |
return $1 + $2.toUpperCase(); | |
}); | |
obj[k] = obj[key]; | |
delete obj[key]; | |
key = k; | |
} | |
toCamel(obj[key]); | |
}); | |
return obj; | |
} | |
console.log(toUnderscore({ | |
fooBar: 1, | |
fooBar2: 2, | |
foo_bar3: 3 | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment