I'm relatively new to JavaScript so please forgive me if this is silly/impossible, but I'm trying to standardize names of properties within a JavaScript object. For example, I have code such as
var object = {
"firstName": "Joe",
"MiddleName": "Roy",
"last_name": "Fool"
}
I want to make a new object that has property names firstName, middleName, and lastName. Is there any way to search through these properties and see which ones are in violation? Otherwise, I could always just make a total copy but that would be quite inefficient. Thanks
This might be going beyond what you're looking for, but it's pretty easy to convert your underscore-separated naming to camelcase; you can iterate over your object and produce a new object with the correct names:
var converter = /_(\w)/g, lowerFirst = /^(\w)/;
function convertName(name) {
if (converter.test(name)) {
name = name.toLowerCase().replace(converter, function ($0, $1) {
return $1.toUpperCase();
});
} else {
// correct a first letter being uppercase
name = name.replace(lowerFirst, function ($0, $1){ return $1.toLowerCase(); });
}
return name;
}
var hasOwnProperty = Object.prototype.hasOwnProperty,
toString = Object.prototype.toString;
function isPlainObject(obj) {
return toString.call(obj) === '[object Object]';
}
function convertObject(obj) {
var k, output = {};
for(k in obj) {
if (hasOwnProperty.call(obj, k)) {
output[convertName(k)] = isPlainObject(obj[k]) ? convertObject(obj[k]) : obj[k];
}
}
return output;
}
If the property names are already in camelcase, they won't be changed by the regexp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With