Search code examples
javascriptobjectjavascript-objects

How to access objects without using if then or case swtich [javascript]


So I created an object prototype like this:

function myObjProto(one, two, three) {
    this.one = one;
    this.two = two;
    this.three = three;  };

Then created a bunch of objects like this:

let myObj1 = new myObjProto (
    /* one */ "one", 
    /* two */ "two", 
    /* three */ "three" );
let myObj2 = new myObjProto (
    /* one */ "one", 
    /* two */ "two", 
    /* three */ "three" );

I have a variable that is changing (myObj1, myObj2, etc) and I know that one way to access the values is to say

let myVar = "myObj";

let var1;
let var2;
let var3;

if (myVar == myObj1){
    var1 = myObj1.one;
    var2 = myObj1.two;
    var3 = myObj1.three;
}
else {
    var1 = myObj2.one;
    var2 = myObj2.two;
    var3 = myObj3.three;
}

But there has to be a better way. I have 7 objects!

I tried something like this:

var1 = myVar.one;
var2 = myVar.two;
var3 = myVar.three;

But all I got was "undefined." Please help.

(The full example is here on JSbin)


Solution

  • You could take an object for all types and take the type as property accessor with brackets.

    var Dwarf = new race(),
        Elf = new race(),
        Gnome = new race(),
        HalfElf = new race(),
        HalfOrc = new race(),
        Halfling = new race(),
        Human = new race(),
        types = { Dwarf, Elf, Gnome, HalfElf, HalfOrc, Halfling, Human },
        type = 'Halfling';
    
    
    // access:
    types[type].language