Created
October 26, 2010 20:00
-
-
Save bentruyman/647655 to your computer and use it in GitHub Desktop.
Dynamic property names in object literals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Can we get something like this?? | |
var howManyRainbows = 'double'; | |
var rainbow = { | |
(howManyRainbows): true | |
}; | |
if (rainbow.double) { | |
alert('What does it mean?'); | |
} |
Only things I can figure, maybe that helps.
var howManyRainbows = 'double';
//First way, but you can call that "multi line declaration"
var rainbow = {};
rainbow[howMayRainbows] = true;
//Second way, but eval is evil
var rainbow = eval('{' + howManyRainbows + ': true }');
if (rainbow[howManyRainbows]) {
alert('What does it mean?');
}
@singles -- the spirit of what's being asked is that it'd be a nice language extension. you're correct there are other ways to accomplish the task, but they're ugly.
I didn't know that Twitter question was about "it would be nice feature" (and gist description also doesn't say that), so I thought it's all about figuring it out. I just wanted to help, my mistake, sorry.
Yep, just as @getify said, there are other ways of accomplishing this in JavaScript, but I'd like to see if anyone else finds something like what I'm doing useful.
For example:
var quxx = {
corge: 1,
grault: false,
(foo): true,
(baz): 9001
};
I'd rather construct my object in one fell swoop, instead of:
var foo = 'bar'
, baz = 'qux';
var quxx = {
corge: 1,
grault: false
};
quxx[foo] = true;
quxx[baz] = 9001;
@singles, my apologies for being vague in my question.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok..so
double
is reserved word. But you get my point!