Home > Enterprise >  get an indexed object with enum as keys
get an indexed object with enum as keys

Time:09-14

I have a list of elements depending each on other, each element has a code(as enum). I want to obtain the list of depending elements of an element, and be able to use myElements[anElementCode]:

enum Code {
  A = 'A',
  B = 'B',
  C = 'C',
  D = 'D',
}

function main() {
  let myElements = [
    { Code.C: [Code.A, Code.B] },
    { Code.D: [Code.B] }
  ]
  console.log(`The Elements on that depends C are: ${myElements[Code.C]}`); 
}

I would like to get from myElements[Code.C] the list [Code.A, Code.B]

Actually such a code does not work, but is there a workaround to make this working?

CodePudding user response:

You're defining myElements as an array but you actually need a dictionary with square brackets to define keys dynamically, try:

function main() {
    let myElements = {
        [Code.C]: [Code.A, Code.B],
        [Code.D]: [Code.B]
    };
    console.log(`The Elements on that depends C are: ${myElements[Code.C]}`); 
}

Playground

  • Related