JS có 2 notation: dot (obj.prop) và bracket (obj['prop']). Bracket notation cho phép dùng **biến** làm key.
Cách 1: Bracket notation (ES5+)
const obj = { a: 'foo' };
const prop = 'bar';
obj[prop] = 'baz';
console.log(obj); // { a: 'foo', bar: 'baz' }
Cách 2: Computed Property Name (ES6)
const prop = 'bar';
const obj = {
a: 'foo',
[prop]: 'baz' // key = value của biến prop
};
console.log(obj); // { a: 'foo', bar: 'baz' }
Lưu ý
- Bracket notation: key được evaluate tại runtime.
- Computed property: chỉ dùng trong object literal.
- Key sẽ được convert to string (Symbol key được giữ nguyên).