2

Let's say I have this:

var ObjectKey = "06.2012";

It's a string that represents the month. I want to use this value as the key of a new object. I have

TheObject = {ObjectKey: null};

But when I go to the console, instead of the TheObject having a key named 06.2012, it has a key named ObjectKey.

How do I create a key that has the name of a string that I create at runtime?

Thanks.

2 Answers 2

9

To use variable as the key you need to use the [] syntax..

var ObjectKey = "06.2012";
TheObject = {};
TheObject[ObjectKey] = null;
Sign up to request clarification or add additional context in comments.

1 Comment

@Kranklin chuckle.. 17 to be exact .. (and James Allardice was second..) :)
-7

quick and dirty:

eval('TheObject = {'+ObjectKey+':null};');

but it's really dirty and susceptible to errors(very suceptible...)

1 Comment

We should note this method could potentially open your website up for attacks. If the ObjectKey is given from the user, e.g. a form variable, then the user could inject JS code to do anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.