如何使用 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' }
廣告