Skip to content

Instantly share code, notes, and snippets.

@sadjow
Created May 10, 2013 00:03
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 sadjow/5551536 to your computer and use it in GitHub Desktop.
Save sadjow/5551536 to your computer and use it in GitHub Desktop.
Update a JavaScript object with a dotted path string. You pass the string path and the object you want.,
// company = {}
// Use putObject("owner.name", company,"Sadjow");
// Returns {owener: {name: "Sadjow"}}
function putObject(path, object, value) {
var modelPath = path.split(".");
function fill(object, elements, depth, value) {
var hasNext = ((depth + 1) < elements.length);
if(depth < elements.length && hasNext) {
if(!object.hasOwnProperty(modelPath[depth])) {
object[modelPath[depth]] = {};
}
fill(object[modelPath[depth]], elements, ++depth, value);
} else {
object[modelPath[depth]] = value;
}
}
fill(object, modelPath, 0, value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment