0

I am trying to write a script that will pull a value from an object, but only the first part of the object name is known, the second part is defined by a seconds variable.

So if I write out the full "Object.values(option_1)1", it will return "Pan" correctly. But if I replace the "_1" with some variable that is equal to "_1" it will not give me the same results unless I use eval().

var option_1 = {
    "First":"Peter",
    "Last":"Pan",
    "Type":"Boy"
};

document.getElementById("demo").innerHTML = Object.values(option_1)[1];

//Does not work
var x = 1
document.getElementById("demo2").innerHTML = Object.values('option_'+x)[1];

//Does not work
var x = 1
var xFull = 'Object.values(option_'+x+')[1]'
document.getElementById("demo3").innerHTML = xFull;

//Does work
var x = 1
var xFullEval = eval('Object.values(option_'+x+')[1]');
document.getElementById("demo4").innerHTML = xFullEval;

Is there any way to get the same results as in the last example but without using eval()? See here: https://jsfiddle.net/h2oczu1d/

------------------------- UPDATE-------------------------

Just to clarify, I tried the solutions in this post, as well as the comments below and all examples with this[] result in undefined. I will try to explain again in more details to see if it will help with a solution:

I will have various predefines sets of options like these already in the code:

    var option_1 = {
    "First":"Peter",
    "Last":"Pan",
    "Type":"Boy"
};

    var option_2 = {
    "Animal":"Cat",
    "Eyes":"Green",
    "Type":"Bengal"
};

Eventually, I will need to access one of the two lists of options, but which list is determined by another variable that is pulled from the DOM (i.e. 2). So if x = 2, I will need to use the options list that ends with a "2", and if x = 1, I will need to use list 1.

var goodMatch = "Type";
var xDom = "2";

for(var i = 0; i < Object.keys(option_[??]).length; i++){   
     if (Object.keys(option_[??])[i] == goodMatch {
          el[i].innerText=Object.values(option_[??])[i];
     }
}

So how do I replace "[??]" in above example with the value of "xDom" so that it accesses the correct options object?

Yevgen
  • 767
  • 2
  • 9
  • 22
  • Where are you getting `option_1` from in the first place? – Dai Feb 14 '18 at 01:47
  • 1
    This is a code smell. You shouldn't be using dynamically created variables. Have you tried using an array? – 4castle Feb 14 '18 at 01:47
  • 1
    Simply use `this['option_' + x]` (`this` being the `window` in your case). It would be much better to use an object or `Map` though to store your _option_ variables in – Phil Feb 14 '18 at 01:47
  • Use a better data structure than the global namespace. – Travis J Feb 14 '18 at 01:47

0 Answers0