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
  • 142,382
  • 31
  • 172
  • 209
Lawrence
  • 10,142
  • 5
  • 39
  • 51

2 Answers2

4

There is, in ES2015:

{
    ['foo']: 123
}

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

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
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
  • 33,467
  • 12
  • 59
  • 101
  • There will be in [*ES6*](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object-initializer). ;-) – RobG Jun 12 '15 at 04:40