• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

Use variable as object name...

When defining an object inside of another object, I'm trying to do this:

{myObject.config.elementID:'foo'}

but it's keeps erroring out on 'myObject.config.elementID' which is a valid var that's set earlier. Can you not use a variable as a name in an array or is there a way to do it?
0
interclubs
Asked:
interclubs
  • 3
  • 2
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
use the "array" way :

myObject[myObject.config.elementID] = 'foo';
0
 
interclubsAuthor Commented:
Still doesn't seem to work, maybe it's something else. This is my code, which appears in a function inside of myObject:

myObject._renderCSSEvents({myObject[myObject.config.elementID] : 'visibility'});

and the error is: Uncaught SyntaxError: Unexpected token [
0
 
leakim971PluritechnicianCommented:

// before creation and init of myObject, myObject.config and myObject.config.elementID

myObject[myObject.config.elementID] = 'visibility';
myObject._renderCSSEvents(myObject.config);

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
ProculopsisCommented:

myObject._renderCSSEvents({myObject[myObject.config.elementID] : 'visibility'});

The problem here is that, unless you prototype type Array or Object, your variable myObject cannot be an array and have methods.
0
 
ProculopsisCommented:

// Alternatively, if I misunderstood your question:

function asObject( key, value ) {
  var result = {};
  result[key] = value;
  return result;
}

myObjectOne._renderCSSEvents( asObject( myObjectTwo[myObjectOne.config.elementID], 'visibility' ) );
0
 
interclubsAuthor Commented:
After much research, it seems that it's not possible to use a variable as a literal object name.

"he limitation of the literal object syntax is that the names has to be literal. As the names can be specified as an identifer as well as a string, it's not possible to use a variable instead."
0
 
interclubsAuthor Commented:
No one else gave the correct answer.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now