Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a concatenated (dynamic) string as JavaScript object key? [duplicate]

var test = "test123" var test123 ={     "key" + test: 123 } 

This code doesn't work. What is wrong with "key" + test ?

like image 942
thinkanotherone Avatar asked Mar 14 '12 18:03

thinkanotherone


People also ask

Can you have duplicate keys in an object JavaScript?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can you concatenate strings in JavaScript?

The concat() function concatenates the string arguments to the calling string and returns a new string.

What is the best way to concatenate strings in JavaScript?

The best and fastest way to concatenate strings in JavaScript is to use the + operator. You can also use the concat() method.

How do you add the same key to an object?

To add multiple key/value pairs to an object in the same statement, use the Object. assign() method. The method copies the key/value pairs of one or more objects into a target object and returns the modified target object.


2 Answers

Because "key" + test is an expression and not an identifier nor a string literal nor a number literal, which are the only things that are allowed as the key in an object literal.

You have to use the [] notation after creating the object for such a dynamic key:

var test123 = {}; test123["key" + test] = 123; 

An identifier is basically the same subset of characters that you can call a variable (letters, numbers, _ and $; may not start with a number), and a string literal is any string enclosed with ' or ".

So, the only types of keys you can use in an object literal are:

{   a0:   true, // valid identifier   $$_:  true, // same   123:  true, // valid numeric literal   012:  true, // same (octal)   0xf:  true, // same (hex)   "@":  true, // not allowed as an identifier   '0a': true  // same } 

Reference: http://es5.github.com/#x11.1.5.

PropertyName :

IdentifierName

StringLiteral

NumericLiteral

like image 199
pimvdb Avatar answered Sep 23 '22 18:09

pimvdb


With ES6, you can define dynamic keys within an object literal:

const test = "test123" const test123 = { [`key${test}`]: 123 };  //{ keytest123: 123 } 
like image 39
Ben Avatar answered Sep 21 '22 18:09

Ben