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';
1
  • 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. Commented Jul 23, 2014 at 22:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Coming in ECMAScript 6 though. {[CONSTANTS.THING_TYPE]: 'whateverType'}
@cookie monster: that's interesting actually! But at first glance looks like using an array as a hash table key (which is valid in some languages/implementations)
Ok thanks. @cookiemonster that would be grat, waiting for it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.