Last active
August 29, 2015 13:57
-
-
Save petersirka/9869367 to your computer and use it in GitHub Desktop.
Assign value by path.
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
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