Skip to content

Instantly share code, notes, and snippets.

@gf3
Created February 19, 2010 19:51
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 gf3/309126 to your computer and use it in GitHub Desktop.
Save gf3/309126 to your computer and use it in GitHub Desktop.
Build object from string.
function build(o, p, v){
var k=[],l,m;
while (m=/(\w+)\.?/g.exec(p)) k.push(m[1]);
for (var i=0; i<k.length; i++) {
l=o;
o=o[k[i]];
}
if (v) l[k[k.length-1]]=v;
return v || o;
}
var test = {a: {b: {c: "lol"}}};
build(test, "a.b.c"); // Returns "lol"
build(test, "a.b.c", "seventeen"); // Sets test.a.b.c to "seventeen" and returns "seventeen"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment