When using Javascript sometimes we need to map a literal string: “My.Nested.Class” to the corresponding object or class.
Below I’ve provided an easy function to determine this, utilizing the underscorejs library. Essentially, this function takes a literal string and an optional “context” argument. The context argument can be used to localalize the object search to a property other than the global “window.” This solution is more efficient than using eval to get the class object from a string.
The function works by iterating over each component of the given string, using “.” as the delimiter. So for example: stringToObject(“My.Object”) works as follows:
- Search for window[My] – if we don’t find a result, return null;
- Search for window[My][Object] – if we find a result return it, otherwise return null
stringToObject = function (path, context) {
var target,
pathSeparator = '.',
scopes = [context || window];
for (var ctx, i = 0, l = scopes.length; i < l; ++i) {
if (ctx = scopes[i]) {
target = _.reduce(path.split(pathSeparator), function (memo, elem) {
return memo[elem];
}, ctx);
if (target) break;
}
}
return target;
}