ใช้ Regex กับ Object.fromEntries() และ Object.entries() แปลง Key
ตัวอย่างโค้ด
var underscoreToCamelCase = str => str.replace(/(_)(.)/g, (_, __, v) => v.toUpperCase());
var JsonObject = {
first_Name_Field: 'John',
last_Name_Field: 'Smith'
};
var output = Object.fromEntries(
Object.entries(JsonObject).map(([key, value]) => [underscoreToCamelCase(key), value])
);
console.log("The JSON Object=");
console.log(output);
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo89.js)
ผลลัพธ์
The JSON Object= { firstNameField: 'John', lastNameField: 'Smith' }