Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bentruyman/647655 to your computer and use it in GitHub Desktop.
Save bentruyman/647655 to your computer and use it in GitHub Desktop.
Dynamic property names in object literals
// Can we get something like this??
var howManyRainbows = 'double';
var rainbow = {
(howManyRainbows): true
};
if (rainbow.double) {
alert('What does it mean?');
}
@bentruyman
Copy link
Author

Ok..so double is reserved word. But you get my point!

@singles
Copy link

singles commented Oct 26, 2010

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?');
}

@getify
Copy link

getify commented Oct 26, 2010

@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.

@singles
Copy link

singles commented Oct 26, 2010

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.

@bentruyman
Copy link
Author

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