1

I would like to specify one of the keys for options to be a value from my constants object but cannot use dot notation inside object declaration.

Is there a shorthand way of doing this without declaring an additional variable before options only to hold the value?

Error:

SyntaxError: missing : after property id

Code:

var constants = {
  KEY: 'Content-Type'
}

var options = {
    constants.KEY: 'application/json'
};
alert(options);
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
  • 1
    try this `[constants.KEY]: 'application/json` – Jan Ciołek Jul 01 '17 at 10:44
  • 2
    Possible duplicate of [How do I add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Andreas Jul 01 '17 at 10:44

1 Answers1

1

As the name of the key is dynamic, you can set the key like the following:

var options = {
   [constants.KEY]: 'application/json'
 };
OmG
  • 18,337
  • 10
  • 57
  • 90