Created
March 15, 2013 23:18
-
-
Save tgvashworth/5173950 to your computer and use it in GitHub Desktop.
Set value at string path of object
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
// Set a value at a string-designated path. | |
// | |
// Takes an object to be modified, a string path ('a.b') and a value to be set | |
// at that path. | |
// | |
// Returns the modified object (although the changes are made in place) | |
var set = function (obj, path, val) { | |
if (!obj || typeof obj !== "object") return obj; | |
if (!path || typeof path !== 'string') return obj; | |
var keys = path.split('.'), | |
level = obj; | |
keys.forEach(function (key, i) { | |
var last = (i === keys.length - 1); | |
if (last) return level[key] = val; | |
if (!level[key] || | |
typeof level[key] !== "object") level[key] = {}; | |
level = level[key]; | |
}); | |
return obj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment