Using value of enum as key in another enum in Javascript

12,490

Solution 1

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' }

Solution 2

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"
};
Share:
12,490
Aayush Kumar
Author by

Aayush Kumar

Entrepreneur. Developer. I love creating things that makes people's lives easier.

Updated on June 06, 2022

Comments

  • Aayush Kumar
    Aayush Kumar about 2 years

    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.

    • thefourtheye
      thefourtheye over 10 years
      Are you going to do this dynamically?
  • Tariq
    Tariq almost 7 years
    Yep! This is known as computing property names: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Germain
    Germain about 5 years
    This should the accepted answer, exactly what I was looking for!