Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  196] [ 5]  / answers: 1 / hits: 15226  / 11 Years ago, sat, january 25, 2014, 12:00:00

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.


More From » dictionary

 Answers
21

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

[#72951] Thursday, January 23, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
whitney

Total Points: 642
Total Questions: 110
Total Answers: 98

Location: Solomon Islands
Member since Mon, Jun 20, 2022
2 Years ago
;