Skip to content

Instantly share code, notes, and snippets.

@petersirka
Last active August 29, 2015 13:57
Show Gist options
  • Save petersirka/9869367 to your computer and use it in GitHub Desktop.
Save petersirka/9869367 to your computer and use it in GitHub Desktop.
Assign value by path.
function assign(obj, path, fn) {
if (obj === null || typeof(obj) === 'undefined')
return obj;
var arr = path.split('.');
var model = obj[arr[0]];
for (var i = 1; i < arr.length - 1; i++)
model = model[arr[i]];
model[arr[arr.length - 1]] = typeof (fn) === 'function' ? fn(model[arr[arr.length - 1]]) : fn;
return obj;
}
// ==============================
// EXAMPLE
// ==============================
var obj = { user: { address: { street: 'Viestova 12' } }, name: 'Peter Širka' };
console.log(obj);
assign(obj, 'user.address.street', 'Teplicka 19');
console.log(obj);
// OR
assign(obj, 'user.name', function(oldvalue) {
return 'Janko Hraško';
});
console.log(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment