You could possibly do something like this.
The first replace
can be used to replace any characters that you want to be markers for upper cased camel casing.
The second replace
performs the camel casing on the letter that follows the marker.
The final replace
makes sure that the first letter of the identifier is lower case.
standardiseProperties
works on the object
in place using the rules of camelCase
. But you could just as well have it return the new object standardised
.
If a name can not be used as it already exists, then the original name is used.
I didn't spend much time on this and there could well be optimisations, or you may wish to change the rules somewhat.
Javascript
function camelCase(string) {
return string.replace(/[-+]/g, "_").replace(/_([\da-z])/gi, function (all, letter) {
return letter.toUpperCase();
}).replace(/^([A-Z])/, function (all, letter) {
return letter.toLowerCase();
});
}
function standardiseProperties(object) {
var standardised = {},
newName,
i;
for (i in object) {
if (object.hasOwnProperty(i)) {
newName = camelCase(i);
if (standardised.hasOwnProperty(newName)) {
standardised[i] = object[i];
} else {
standardised[newName] = object[i];
}
delete object[i];
}
}
for (i in standardised) {
object[i] = standardised[i];
}
}
var object = {
"firstName": "Joe",
"MiddleName": "Roy",
"last_name": "Fool"
};
console.log(object);
standardiseProperties(object);
console.log(object);
Output
Object {firstName: "Joe", MiddleName: "Roy", last_name: "Fool"}
Object {firstName: "Joe", middleName: "Roy", lastName: "Fool"}
On jsfiddle