0

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.

johntrepreneur
  • 4,514
  • 6
  • 39
  • 52

1 Answers1

1

Is it really worth it to save one line? I guess if you really want to be hacky, you could do this:

var myKey = 'text';
var myObj = JSON.parse( '{"' + myKey + '": "Hello"}' );
alert(myObj.text);

I would actually just declare the object and set the key

var myKey = 'text';
var myObj = {};
myObj[myKey] = "Hello";
alert(myObj.text);
Will
  • 2,604
  • 2
  • 18
  • 14
  • You're right if it's just saving one line, but when there are many occurrences, it doubles your lines (per the example). And this is fine if there's no good alternative, but I wanted to see what the SO js community experts had to say about it. – johntrepreneur Aug 27 '13 at 16:06