如何使用JavaScript修改对象中的键值并删除下划线?
为了修改键值,您需要使用正则表达式以及Object.fromEntries()。
示例
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);要运行以上程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo89.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\JavaScript-code> node demo89.js
The JSON Object=
{ firstNameField: 'John', lastNameField: 'Smith' }