JS มี 2 notations สร้าง object properties: dot notation และ bracket notation
สร้าง object property จาก variable ต้องใช้ bracket notation
ตัวอย่าง
const obj = {a: 'foo'} const prop = 'bar' // Set the property bar using the variable name prop obj[prop] = 'baz' console.log(obj);ผลลัพธ์
{ a: 'foo', bar: 'baz' }ES6 introduces computed property names ทำได้:
ตัวอย่าง
const prop = 'bar' const obj = { // Use a as key a: 'foo', // Use the value of prop as key [prop]: 'baz' } console.log(obj);ผลลัพธ์
{ a: 'foo', bar: 'baz' }