2

var string = 'object.data.path';

That's a string that resembles a path to variable.

How can I return the corresponding variable from that string?

Something like transforming the string into return object.data.path;

The thing behind this is that the string could be much longer (deeper), like:

var string = 'object.data.path.original.result';

tomsseisums
  • 13,168
  • 19
  • 83
  • 145

2 Answers2

3
function GetPropertyByString(stringRepresentation) {
    var properties = stringRepresentation.split("."),
        myTempObject = window[properties[0]];
    for (var i = 1, length = properties.length; i<length; i++) {
    myTempObject = myTempObject[properties[i]];
    }

    return myTempObject;
}


alert(GetPropertyByString("object.data.path"));

this assumes that your first level object (in this case called object is global though. Alternatively, although not recommended, you could use the eval function.

Dennis
  • 14,210
  • 2
  • 34
  • 54
3

Assuming you don't want to just use eval you could try something like this:

function stringToObjRef(str) {
   var keys = str.split('.'),
       obj = window;
   for (var i=0; i < keys.length; i++) {
      if (keys[i] in obj)
         obj = obj[keys[i]];
      else
         return;
   }

   return obj;
}

console.log(stringToObjRef('object.data.path.original.result'));

Uses a for loop to go one level down at a time, returning undefined if a particular key in the chain is undefined.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Thanks, award given to Chips_100 due to lower reputation. A bonus tho' for undefined return. – tomsseisums Sep 28 '11 at 13:14
  • Thanks. (Must've been that extra time I spent thinking about the undefined test that let Chips_100 answer before me.) Regarding your comment to Chips about looking for a way to do it without loops, you can do it with function recursion... – nnnnnn Sep 28 '11 at 13:19
  • Function recursion is still a loop, just, not a "documented" one. – tomsseisums Sep 28 '11 at 13:25
  • 1
    Yeah, I know. And for this purpose I think a standard for loop is simpler. Some more reading that I just found from the related list on the right (includes an answer using `reduce`): http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference – nnnnnn Sep 28 '11 at 13:30