JQuery Convert string to object without eval ()

I have the following variables:

    var opday = [],
        opcategory = [],
        opbarrio = [];

      

Then I have another:

        var myparent = $me.parent().attr('data-filter-group');

      

Assuming myparent returns "category", how can I create an object from this string that refers to a variable opcategory

?

For example:

var myarray = "op" + myparent;

      

So that I can use this object like this:

alert(myarray[2]);

      

Thank!

+3


source to share


3 answers


You can access variables declared in the global scope like:

var myCustomVar = "my value"
, nameOfVar = "myCustomVar"
alert(this[nameOfVar])
// you get "my value"

      

However, this doesn't work if you paste it inside a function:



var answer = (
    function(){
        var myvar = "the value"
        return this["myvar"]
    }
).call({})
// answer will be 'undefined'

      

Explicitly linking vars to objects this

works, though:

var answer = (
    function(){
        this.myvar = "the value"
        return this["myvar"]
    }
).call({})
// 'answer' will be "the value"

      

+2


source


I think the best solution for this is an object:

var op = {
  day: [],
  category: [],
  barrio: []
};

      

What can you do like this:



var myarray = op[myparent];

      

There's also a less elegant solution (read: evil and hacky) that only works if opday

and the rest are global variables. All global variables are properties of an object window

that allows you to dynamically create and access variables:

var myarray = window["op" + myparent];

      

+3


source


If you need to get a global variable by name, do this:

var myarray = window["op"+myparent];

      

but it would be much better to put all of them in a map object.

+2


source







All Articles