Skip to content
Advertisement

JavaScript set anonymous Object key to variable name

JavaScript

However, this yields an object with a key of “key”! How can I create a new object with a key of the value of the variable key?

Advertisement

Answer

You can do this:

JavaScript

There’s no way to do it in JavaScript within the object literal itself; the syntax just doesn’t provide for that.

edit — when this answer was written, the above was true, but ES2015 provides for dynamic keys in object initializers:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement