Ken
Ken

Reputation: 636

Adding dynamic variables in object keys

Is something like this allowed in Javascript:

var object = {
    'key1' + var1 : 'value',
    'key2' + var1 : 'value'
};

I'd liked to concat the var1 variable with the key but I'm getting a syntax error. Here's the full error:

Uncaught SyntaxError: Unexpected token + 

Upvotes: 0

Views: 29

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

No, obviously(You are getting an error),

But you can do this:

var obj = {};
obj["key1" + var1] = 'value';

It's using bracket notation to set the dynamic so called key

Upvotes: 2

Related Questions