Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  36] [ 6]  / answers: 1 / hits: 20543  / 9 Years ago, sun, june 21, 2015, 12:00:00

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?


More From » regex

 Answers
5

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

[#66106] Friday, June 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;