Skip to content
Advertisement

Convert javascript object camelCase keys to underscore_case

I want to be able to pass any javascript object containing camelCase keys through a method and return an object with underscore_case keys, mapped to the same values.

So, I have this:

var camelCased = {firstName: 'Jon', lastName: 'Smith'}

And I want a method to output this:

{first_name: 'Jon', last_name: 'Jon'}

What’s the fastest way to write a method that takes any object with any number of key/value pairs and outputs the underscore_cased version of that object?

Advertisement

Answer

Here’s your function to convert camelCase to underscored text (see the jsfiddle):

function camelToUnderscore(key) {
    return key.replace( /([A-Z])/g, "_$1").toLowerCase();
}

console.log(camelToUnderscore('helloWorldWhatsUp'));

Then you can just loop (see the other jsfiddle):

var original = {
    whatsUp: 'you',
    myName: 'is Bob'
},
    newObject = {};

function camelToUnderscore(key) {
    return key.replace( /([A-Z])/g, "_$1" ).toLowerCase();
}

for(var camel in original) {
    newObject[camelToUnderscore(camel)] = original[camel];
}

console.log(newObject);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement