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';
-
Where is the string coming from?Dennis– Dennis2011年09月28日 13:01:33 +00:00Commented Sep 28, 2011 at 13:01
-
HTML5 data attribute name, dashes replaced with dots.tomsseisums– tomsseisums2011年09月28日 13:07:18 +00:00Commented Sep 28, 2011 at 13:07
2 Answers 2
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.
2 Comments
myTempObject is still an object, and only then retrieve its property...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
reduce): stackoverflow.com/questions/6393943/…