Created
April 14, 2014 15:41
-
-
Save brigand/10659453 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function set(obj, keys, value){ | |
// for empty or undefined paths, just assume root | |
if (!keys) { | |
return obj; | |
} | |
var parts = keys.split("."), o = obj; | |
for (var i=0; i < parts.length - 1; i++) { | |
var part = parts[i]; | |
if (typeof o !== "object") { | |
return false; | |
} | |
o = o[part]; | |
} | |
if (typeof o === "undefined") { | |
return false; | |
} | |
o[parts[parts.length - 1]] = value; | |
} | |
// for example: | |
var o = { | |
b: ["a", "b", "c"], | |
d: { | |
e: { | |
q: 1 | |
} | |
} | |
} | |
set(o, "b.2") // => "c" | |
set(o, "d.e.q") // => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment