Skip to content

Instantly share code, notes, and snippets.

@nanch
Created February 27, 2017 15:30
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 nanch/a336f1154d87dc7c6d8b910d29286c66 to your computer and use it in GitHub Desktop.
Save nanch/a336f1154d87dc7c6d8b910d29286c66 to your computer and use it in GitHub Desktop.
Mapping properties of javascript objects from under_score to camelCase and back again
String.prototype.toCamel = function () {
return this.replace(/(_[a-zA-Z])/g, function ($1) {
return $1.toUpperCase().replace('_', '');
});
};
String.prototype.toUnderscore = function () {
return this.replace(/([A-Z])/g, function ($1) {
return "_" + $1.toLowerCase();
});
};
function withCamelCaseKeys(obj) {
const newObjectWithCamelCaseKeys = {}
for (const key of Object.keys(obj)) {
if (obj[key] !== null && typeof obj[key] === 'object') {
newObjectWithCamelCaseKeys[key.toCamel()] = withCamelCaseKeys(obj[key])
} else {
newObjectWithCamelCaseKeys[key.toCamel()] = obj[key]
}
}
return newObjectWithCamelCaseKeys
}
function withUnderscoreKeys(obj) {
const newObjectWithUnderscoreKeys = {}
for (const key of Object.keys(obj)) {
if (obj[key] !== null && typeof obj[key] === 'object') {
newObjectWithUnderscoreKeys[key.toUnderscore()] = withUnderscoreKeys(obj[key])
} else {
newObjectWithUnderscoreKeys[key.toUnderscore()] = obj[key]
}
}
return newObjectWithUnderscoreKeys
}
let obj = {camel_case_test: 123, object_test: {child_object_test_key: "test", child_object_test_key2: "test2"}}
const newThing = withCamelCaseKeys(obj)
console.debug(newThing)
const newThing2 = withUnderscoreKeys(newThing)
console.debug(newThing2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment