chuckp chuckp - 2 months ago 28
Javascript Question

convert javascript enum key string to value

In JavaScript code, I have the following enum defined:

MyMessageIds = {
UndefinedId : 0,
FilenameId : 1,
BuildFileId : 2,
MovementArgsId : 3,
MoveId : 4,
ExecuteCommandId : 5
}


In a JavaScript function, I would like to be able to supply the string representation of an enum key (i.e. "MoveId") and return its integer value of 4. So how could I do this?

Answer

Just use bracket notation:

var MyMessageIds = {
    UndefinedId : 0,
    FilenameId : 1,
    BuildFileId : 2,
    MovementArgsId : 3,
    MoveId : 4,
    ExecuteCommandId : 5
};

function getValue(key) {
    return MyMessageIds[key];
}