Skip to content

Instantly share code, notes, and snippets.

@brigand
Created April 14, 2014 15:41
Show Gist options
  • Save brigand/10659453 to your computer and use it in GitHub Desktop.
Save brigand/10659453 to your computer and use it in GitHub Desktop.
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