Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to modify key values in an object with JavaScript and remove the underscore?
In JavaScript, you can modify object keys to remove underscores and convert them to camelCase using regular expressions combined with Object.fromEntries() and Object.entries().
Syntax
const camelCaseKey = str => str.replace(/(_)(.)/g, (_, __, char) => char.toUpperCase());
const newObject = Object.fromEntries(
Object.entries(originalObject).map(([key, value]) => [camelCaseKey(key), value])
);
Example
// Function to convert underscore keys to camelCase
var underscoreSpecifyFormat = str => str.replace(/(_)(.)/g, (_, __, v) => v.toUpperCase());
// Original object with underscore keys
var JsonObject = {
first_Name_Field: 'John',
last_Name_Field: 'Smith'
};
// Transform the object keys
var output = Object.fromEntries(
Object.entries(JsonObject).map(([key, value]) => [underscoreSpecifyFormat(key), value])
);
console.log("The JSON Object=");
console.log(output);
The JSON Object=
{ firstNameField: 'John', lastNameField: 'Smith' }
How It Works
The transformation process involves three key steps:
-
Object.entries()converts the object into an array of [key, value] pairs - The
map()method transforms each key using the regex pattern/(_)(.)/g -
Object.fromEntries()reconstructs the object with the modified keys
Multiple Underscore Example
var convertToCamelCase = str => str.replace(/(_)(.)/g, (_, __, char) => char.toUpperCase());
var complexObject = {
user_first_name: 'Alice',
user_last_name: 'Johnson',
account_creation_date: '2023-01-15',
is_active_user: true
};
var result = Object.fromEntries(
Object.entries(complexObject).map(([key, value]) => [convertToCamelCase(key), value])
);
console.log(result);
{
userFirstName: 'Alice',
userLastName: 'Johnson',
accountCreationDate: '2023-01-15',
isActiveUser: true
}
Conclusion
Use Object.fromEntries() with Object.entries() and regex replacement to efficiently transform object keys from underscore notation to camelCase. This approach preserves all values while modifying only the key structure.
Advertisements
