Skip to content

Instantly share code, notes, and snippets.

@tgvashworth
Created March 15, 2013 23:18
Show Gist options
  • Save tgvashworth/5173950 to your computer and use it in GitHub Desktop.
Save tgvashworth/5173950 to your computer and use it in GitHub Desktop.
Set value at string path of object
// 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