Advertisement
Guest User

Setting an object proper by path

a guest
Jan 2nd, 2017
927
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // var o = { success: true }
  2. // Object.setByPath('data.person.name', o, 'Mike')
  3. // => { success: true, data: { person: { name: 'Mike'} } }
  4. Object.setByPath = function(path, obj, value) {
  5.   var parts = path.split('.');
  6.   return parts.reduce(function(prev, curr, ix) {
  7.     return (ix + 1 == parts.length)
  8.       ? prev[curr] = value
  9.       : prev[curr] = prev[curr] || {};
  10.   }, obj);
  11. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement