Monday, 26 August 2013

How to use dynamic key name in object during object construction?

How to use dynamic key name in object during object construction?

I want to use a dynamic key name during the creation of the object.
var myKey = 'text';
var myObj = {
[myKey]: 'Hello' // not working
};
alert(myObj.text);
I know you can do it on the next line after the object is created
myObj[key] = 'someValue', but I was curious about doing it when you're
creating the object.
There's a plethora of similar questions about it, but they all do it after
the object has been created using the [] notation.

No comments:

Post a Comment