Created
May 10, 2013 00:03
-
-
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.,
This file contains hidden or 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
// 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