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

2
  • Where is the string coming from? Commented Sep 28, 2011 at 13:01
  • HTML5 data attribute name, dashes replaced with dots. Commented Sep 28, 2011 at 13:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Already made a similar function, but asked in hope that there's a different way except loops..
For each iteration, you should check if myTempObject is still an object, and only then retrieve its property...
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.

4 Comments

Thanks, award given to Chips_100 due to lower reputation. A bonus tho' for undefined return.
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...
Function recursion is still a loop, just, not a "documented" one.
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): stackoverflow.com/questions/6393943/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.