You can use bracketed notation:
var obj = {};
obj[prop] = 1;
console.log(obj);
In JavaScript, you can refer to a property either by dot notation and a literal name (foo.bar
), or bracketed notation with a string name (foo["bar"]
). In the latter case, the string can be the result of any expression, including (in your case) a variable reference.
...but what I'm really looking for is a one-liner.
There's no way to do that as part of an object initializer, though, you have to do it separately. If you want a one-liner, you'll need to do a function call, e.g.:
console.log(makeObj(prop, 1));
where makeObj
is
function makeObj(propName, propValue) {
var obj = {};
obj[propName] = propValue;
return obj;
}