Take the below object:
var value = 'bar';
var obj = { foo: value }
// -> Object { foo="bar" }
Supposing the key was also a variable, one could go:
var key = 'foo', value = 'bar';
var obj = {}
obj[key] = value;
// -> Object { foo="bar" }
Now, I want to do this in one line (shorthand). So I tried:
var obj = {}[key] = value; // or,
var obj = ({})[key] = value; // or,
var obj = new Object()[key] = value;
// -> "bar"
This oddly produces a String instead of an Object.
Is there any way to do this shorthand?
var obj = new Object()[key] = value;
is better thanvar obj = {}; obj[key] = value;
? – Disembodyobj = {[key]: value}
– Initiatevar obj = (function(o) {o[key]=value; return o})({});
is a good shorthand forvar obj = {}; obj[key] = value
? – Eclogue