0

I have an object holding some of my program constants so that I can use it in all of the source code files. The constants object is something like this:

CONSTANTS = {
  THING_TYPE: 'type',
  THING_INFORMATION: 'information',
  THING_DESCRIPTION: 'description',
  THING_NAME: 'name',
  manyOtherConstants
}

And I want to create objects using a similar notation and using the value of the constants as a property of the object; this is what I'm trying to do:

var myObject = {
  CONSTANTS.THING_TYPE: 'whateverType',
  CONSTANTS.THING_INFORMATION: {
    CONSTANTS.THING_DESCRIPTION: 'whateverDescription',
    CONSTANTS.THING_NAME: 'whateverName',
  }
}

The problem is that I cannot use the constants in that way. Javascript says:

'SyntaxError: missing : after property id'

Is there any way of doing what I am trying to do using that notation? Or is the only thing that I can do is the following?

var myObject = {}
myObject[CONSTANTS.THING_TYPE] = 'whateverType';
myObject[CONSTANTS.THING_INFORMATION] = {};
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_DESCRIPTION] = 'whateverDescription';
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_NAME] = 'whateverName';
cookie monster
  • 10,671
  • 4
  • 31
  • 45
sergioFC
  • 5,926
  • 3
  • 40
  • 54
  • So, without using `eval` I think you could go with building an object string the way you want (1st paragraph) and then `JSON.parse` it. – Sebas Jul 23 '14 at 22:58

1 Answers1

1

No you cannot do that using object literal initialization syntax.

So the only way is to use what you do in the second case - using [...] notatin.

zerkms
  • 249,484
  • 69
  • 436
  • 539