1

i.e.:

assert(createObj('foo', 5)) == {foo: 5}

One implementation would of course be:

function createObj(key, val) {
  var ret = {};
  ret[key] = val;
  return ret;
}

Just wondering if there's a one-liner.

RobG
  • 134,457
  • 30
  • 163
  • 204
lawrence
  • 9,239
  • 5
  • 37
  • 50

2 Answers2

4

There is, in ES2015:

{
    ['foo']: 123
}

And there is no really simple and "fair" one in ES5.1

References:

zerkms
  • 240,587
  • 65
  • 429
  • 525
0

It looks like is not possible in pure JavaScript. You need to make the object first, then use [] to set it.

However, is possible in frameworks. For instance, in ES.

Using a variable for a key in a JavaScript object literal

JavaScript set object key by variable

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 32,279
  • 11
  • 59
  • 94
  • There will be in [*ES6*](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object-initializer). ;-) – RobG Jun 12 '15 at 04:40