Aayush Kumar Aayush Kumar - 16 days ago 7
Javascript Question

Using value of enum as key in another enum in Javascript

I have an enum:

var a = {X: 0, Y: 1};


And, I want to create another enum from the values of the first one. Something like this:

var b = {a.X: "foo", a.Y: "bar"};


Doing this gives me a
SyntaxError: Unexpected token .


Is there a way I can use the values of one enum as the key to another in javascript?

FYI: I realize I can do something like this to achieve what I want

var b = {};
b[a.X] = "foo";
b[a.Y] = "bar";


But, from a readability perspective, I would prefer if there was some way to do it the former way.

Answer

Nope, you gotta do it the second way.

To understand the reason for this, consider this code:

var foo = 'bar';

var object = {
  foo: 'baz'
};

In the object literal, is foo the value stored in the variable foo or the string "foo"?

According to the rules of the language, it's the latter. So the keys of an object expression can't be complex expressions themselves.

The closest you might come in terms of readability would be to write a helper along these lines:

function mapKeys(object, keyMapping) {
  var mapped = {};
  for (var key in keyMapping) {
    mapped[object[key]] = keyMapping[key];
  }
  return mapped;
}

var a = { X: 0, Y: 1 };

var b = mapKeys(a, {
  X: 'foo',
  Y: 'bar'
});
// => { 0: 'foo', 1: 'bar' }