0

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 + 
3
  • When you are not sure if its ok or not, try it in the developer console. Commented Apr 17, 2014 at 16:20
  • @phylax Probably OP has tried, syntax errors don't occur without doing something wrong ; ). Commented Apr 17, 2014 at 16:22
  • This is relatively often asked question, just pick your dup... Commented Apr 17, 2014 at 16:27

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.