1

I never thought I'd stumble in a problem like that but hey what do you know..

var prop = 'horses'

console.log({
    prop: 1
});

How can I have this produce an object with a property horses instead of prop and possibly have it done in a single line? Because I can think of a solution but what I'm really looking for is a one-liner.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

2 Answers2

3

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;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Try using JSON to create the object:

console.log(JSON.parse("{\"" + prop + "\":\"1\"}");
Bic
  • 3,141
  • 18
  • 29