Why does Javascript syntax not support inline object literals with a variable property? For example:
const f = function (arg) {
console.log(arg);
}
f({}['some key'] = 1) // 1
f({ 'some key' : 1}) // [object Object] { some key: 1 }
Is there another alternative other than the two steps?
var o = {}
o['some key'] = 1
f(o)
Thanks!
Why does Javascript syntax not support inline object literals with a variable property? For example:
const f = function (arg) {
console.log(arg);
}
f({}['some key'] = 1) // 1
f({ 'some key' : 1}) // [object Object] { some key: 1 }
Is there another alternative other than the two steps?
var o = {}
o['some key'] = 1
f(o)
Thanks!
Share asked Dec 10, 2015 at 14:15 donnie_armstrongdonnie_armstrong 1,3833 gold badges11 silver badges8 bronze badges 2-
is there a problem with
var o = { 'some key' : 1}
? if you mean property name contained in variable it's ES6 – Hacketo Commented Dec 10, 2015 at 14:25 - Correct, sorry that is not reflected in the example. – donnie_armstrong Commented Dec 10, 2015 at 14:31
1 Answer
Reset to default 11Why does Javascript syntax not support inline object literals with a variable property?
You seem to be asking about variable properties, yet your examples do not use variables. Specifically, this example will work just fine.
f({ 'some key' : 1})
However, if you actually did want to use a variable without first creating the object, ECMAScript 6 now allows this.
So if this is your variable:
var my_variable = 'some key';
You can now use square brackets around the property name in the object literal, and it will use the value of the expression you provide:
var o = {[my_variable]: 1};
The o
object will have a property named "some key"
. This only works in the implementations that support this syntax of course.