Skip to content

Instantly share code, notes, and snippets.

@petersirka petersirka/assign.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.