4

Using this technique to setup enums in javascript, I would now like to search based on some other variable in my function below.

Here's the enum config:

var enums_instrumentType = Object.freeze({
    CASH: 0,
    EQUITY: 1,
    COMPOSITE_INDEX:2 ,
    EXCHANGE_RATE:3 ,
    IR_INDEX: 4,
    IR_SWAP_INDEX: 5
});
var enums_tenorUnit = Object.freeze({
      DAY: 0,
      WEEK: 1,
      MONTH: 2,
      YEAR: 3
});

function test(){
   thisInstr = _.findWhere(instrumentsList, { id: mem.instrument_id });  // FIND IT !
   var tenor_unit = thisInstr.ir_index.tenor.unit;     // 0: DAY, 1: WEEK, etc.
   var tenor_size = thisInstr.ir_index.tenor.size;     // number of units

   // HOW TO LOOKUP tenor_unt IN enums_tenorUnit, where tenor_unit is an integer value ???

}

thanks in advance... Bob

bob.mazzo
  • 5,183
  • 23
  • 80
  • 149
  • You're looking for the `[ ]` operator. – Pointy Dec 17 '13 at 22:32
  • 1
    [See this other question](http://stackoverflow.com/questions/16417864/accessing-object-properties-where-the-property-name-is-in-a-variable) (or many others like it). – Pointy Dec 17 '13 at 22:33
  • i think you have it backwards, it seems like you want to convert a number to a string: ["day","week","month"][1] == "week" – dandavis Dec 18 '13 at 03:02

1 Answers1

3

assuming tenor_unit is something like 0 or 1:

var numericValue = _.keys(enums_tenorUnit)[tenor_unit];

however, if tenor_unit is something like DAY or WEEK then simply:

var numericValue = enums_tenorUnit[tenor_unit];

alternatively, if you're looking for a boolean result rather than the literal value and if tenor_unit is something like DAY or WEEK you could use the in operator:

var tenorUnitExists = tenor_unit in enums_tenorUnit;
zamnuts
  • 9,492
  • 3
  • 39
  • 46
  • 1
    tenor_unit is an integer value, so this worked: var tenorName = _.keys(enums_tenorUnit)[tenor_unit]; (where tenor_unit=0, 'DAY' was returned. – bob.mazzo Dec 18 '13 at 17:36
  • I have a related questions regarding how I can move those enum defs into an enums.js file. I'm using Durandal framework. Perhaps I'll just post a new questions. – bob.mazzo Dec 18 '13 at 17:40
  • @bob, I don't have any experience with the Durandal fwk, it is in your best interest to post another question anyway. – zamnuts Dec 18 '13 at 17:57