Skip to content

Instantly share code, notes, and snippets.

@chjj
Created August 1, 2012 17:33
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 chjj/3229094 to your computer and use it in GitHub Desktop.
Save chjj/3229094 to your computer and use it in GitHub Desktop.
toUnderscore and toCamel functions
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