Skip to content

Instantly share code, notes, and snippets.

@victor-github
Created May 24, 2011 16:23
Show Gist options
  • Save victor-github/989053 to your computer and use it in GitHub Desktop.
Save victor-github/989053 to your computer and use it in GitHub Desktop.
Given a string of form field1.field2.field3..., parses it and returns "" if at any point the fields are not defined, or the value of the evaluation if all fields are defined
// usage: ifDefined("field1.field2.field3") - do not specify second argument
ifDefined: function(str_object, prev_eval) {
var i = str_object.indexOf('.');
if (i === -1) {
return true;
} else {
var first = str_object.substring(0,i),
last = str_object.substring(i+1),
j = last.indexOf('.'),
second = last;
if (j !== -1) {
second = last.substring(0,j);
}
if (typeof prev_eval !== "undefined") {
first = prev_eval;
}
eval_result = eval(first)[second];
if (typeof eval_result != "undefined") {
var recurse = this.ifDefined(last, eval_result);
if (recurse === true) {
return eval_result; //return last eval if returning from base case
} else {
return recurse; //otherwise, pass the eval back
}
} else {
return "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment