P粉1166544952023-08-25 16:58:11
With ECMAScript 2015, you can use square bracket notation directly in the object declaration:
var obj = { [key]: value }
Where key
can be any type of expression (such as a variable), returning a value:
var obj = { ['hello']: 'World', [x + 2]: 42, [someObject.getId()]: someVar }
P粉6966058332023-08-25 10:28:30
You can use the equivalent syntax:
obj[name] = value
Example:
let obj = {}; obj["the_key"] = "the_value";
Or use ES6 features:
let key = "the_key"; let obj = { [key]: "the_value", };
In both examples, console.log(obj)
will return: { the_key: 'the_value' }