开发者

string as object reference to object variable

开发者 https://www.devze.com 2023-04-09 15:15 出处:网络
var string = \'object.data.path\'; Th开发者_如何学JAVAat\'s a string that resembles a path to variable.

var string = 'object.data.path';

Th开发者_如何学JAVAat'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';


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号