cyberwombat
cyberwombat

Reputation: 40084

Push an object with a property to an array

How can I do this in one line:

var u = { code: 'foo' };
var a = [];
var o = {};
o[u.code] = 'bar';
a.push(o);

The following, which I would have assumed to work, are invalid:

a.push({ u.code: 'bar' });
a.push({ u['code']: 'bar' });

I may be just having a brainfart here...

Upvotes: 0

Views: 74

Answers (2)

Alcides Queiroz
Alcides Queiroz

Reputation: 9576

Felix Kling's answer is totally correct, though there's a dirty alternative to do what you want in just one line (Don't tell anyone I told you to do this kind of thing =P):

a.push(JSON.parse('{"{0}": "bar"}'.replace('{0}', u.code)))

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

The shortest you can make the code in ES5 is:

var u = { code: 'foo' }, a = [{}];
a[0][u.code] = 'bar';

Once computed properties are supported by browsers (coming in ES6), you can use:

var u = { code: 'foo' }, a = [{[u.code]: 'bar'}];

You can also use ES6 syntax today and transpile it to ES5.

Upvotes: 1

Related Questions