Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 658
Aayush Kumar Avatar asked Feb 01 '26 03:02

Aayush Kumar


2 Answers

I just came across this whilst looking for something else...

You can now do this with ES6 syntax

var b = {
    [a.X]: "foo", 
    [a.Y]: "bar"
};
like image 142
T Mitchell Avatar answered Feb 02 '26 17:02

T Mitchell


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' }
like image 36
Dan Tao Avatar answered Feb 02 '26 19:02

Dan Tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!