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:





source to share

3 answers

You can access variables declared in the global scope like:

var myCustomVar = "my value"
, nameOfVar = "myCustomVar"
// you get "my value"


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

var answer = (
        var myvar = "the value"
        return this["myvar"]
// answer will be 'undefined'


Explicitly linking vars to objects this

works, though:

var answer = (
        this.myvar = "the value"
        return this["myvar"]
// 'answer' will be "the value"




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];




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.



All Articles