Variable variable in js

I need to create a variable name of a variable in JS ...

obj = {};
obj.fooonex = {};
obj.fooonex.start = 1;
obj.fooonex.end = 2;

a = "foo";
b = "one";
c = "x";

test = a + b + c;

alert(obj.test.start);

I want the result to be "1"

fiddle here: http://jsfiddle.net/mR6BH/

+5
source share
2 answers

You need to do:

alert(obj[test].start);
+10
source

generic 2 fixes i.e. more reliable solution

initial! even every thing is like a string !!!
From the above problem, I am extending objectname, propertyname is a Jang string! ...

objectname = "obj";
propertyname = "start";

// try the notification (get (objectname + "." + test + "." + property name));

function get(path) {
    var next = window;

    path = path.split(/[\[\]\.]+/);

    if (path[path.length - 1] == "") {
        path.pop();
    };

    while (path.length && (next = next[path.shift()]) && typeof next === "object" && next !== null);

    return path.length ? undefined : next;
}

Other

   function getPropertyValueByPath (obj, path)
    {
        path = path.split(/[\[\]\.]+/);

        if(path[path.length - 1] == "")
        {
            path.pop();
        };

        while(path.length && ( obj = obj[path.shift()]));

        return obj;
    }

Using

 alert(getPropertyValueByPath(obj,test+ "." + propertyname ));
 alert(get(objectname + "." + test + "." +propertyname));

Non recommented way

eval(objectname + "." + test + "." +propertyname )

Another way `eval("obj." + test + ".start")`
a way of insecure and non-advised eval()
-1
source

All Articles