How to modify key values in an object with JavaScript and remove the underscore?


In order to modify the key values, you need to use regular expressions along with Object.fromEntries().

Example

var underscoreSpecifyFormat = str => str.replace(/(_)(.)/g, (_, __, v)
=> v.toUpperCase()),
JsonObject = { first_Name_Field: 'John', last_Name_Field: 'Smith'},
output = Object.fromEntries(Object.entries(JsonObject).map(([key, value]) => [underscoreSpecifyFormat(key), value]));
console.log("The JSON Object=");
console.log(output);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo89.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo89.js
The JSON Object=
{ firstNameField: 'John', lastNameField: 'Smith' }

Updated on: 07-Sep-2020

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements