Computed Property Name: ใช้ค่าตัวแปรเป็น Key ของ Object
ห่อตัวแปรด้วย [] ใน object literal เพื่อใช้ค่าของตัวแปรเป็น key
ตัวอย่างโค้ด
var name = "David";
var putTheAllData = [];
// Key เป็นตัวอักษร 'name' ตรงตัว
putTheAllData.push({
name: "The name is name will remain same"
});
// Key เป็นค่าของตัวแปร name คือ "David"
putTheAllData.push({
[name]: "The name is David will be changed [name]"
});
console.log(putTheAllData);
วิธีรัน
node fileName.js
ผลลัพธ์
[
{ name: 'The name is name will remain same' },
{ David: 'The name is David will be changed [name]' }
]
คำอธิบาย
- โดยไม่มี
[]: key จะเป็น string literal"name" - มี
[name]: key จะเป็นค่าของตัวแปรnameคือ"David" - เรียกว่า Computed Property Names (ES2015+)
การประยุกต์ใช้ทั่วไป
const key = 'dynamicKey';
const obj = {
[key]: 'value',
['prefix_' + key]: 'another value'
};
// { dynamicKey: 'value', prefix_dynamicKey: 'another value' }