JMac JMac - 1 year ago 150
Javascript Question

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?

Answer Source

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

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


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];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download