Created
February 27, 2017 15:30
-
-
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
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
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