Skip to content

Instantly share code, notes, and snippets.

@agibralter
Created April 8, 2010 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agibralter/360480 to your computer and use it in GitHub Desktop.
Save agibralter/360480 to your computer and use it in GitHub Desktop.
var val1, val2, val3, str, obj;
str = "info.first_name";
obj = {
info: {
first_name: "Bob"
}
};
val1 = eval("(obj."+str+")");
val2 = (new Function('obj', 'return obj.' + str + ';'))(obj)
for(i = 0, val3 = obj; val3 != undefined && i < str.split(".").length; val3 = val3[str.split(".")[i]], i++);
console.log(val1); // Bob
console.log(val2); // Bob
console.log(val3); // Bob
fetchInObj = function (obj, str) {
var val, arr;
arr = str.split(".");
for(i = 0, val = obj; val != undefined && i < arr.length; val = val[arr[i]], i++);
return val;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment