Skip to content

Instantly share code, notes, and snippets.

@kane-thornwyrd
Last active April 17, 2019 03:19
Show Gist options
  • Save kane-thornwyrd/44fdc43c63eccbd5a057 to your computer and use it in GitHub Desktop.
Save kane-thornwyrd/44fdc43c63eccbd5a057 to your computer and use it in GitHub Desktop.
How to browse and tweak objects using a string path. 😄 (require Underscore.js for the _.isString)
var target = {
foo: {
bar: {
baz: [
'madness'
]
}
}
};
deepAccess(target, 'foo.bar.baz').push('sparta');
console.log(target) //→ {foo:{bar:{baz:['madness', 'sparta']}}}
function deepAccess(obj, path){
if(_.isString(path)){
path = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
}
return path.length === 1 ? obj[path.shift()] : deepAccess(obj[path.shift()], path);
}
@kane-thornwyrd
Copy link
Author

Underscore-less version

function deepAccess(obj, path){
  if(Object.prototype.toString.call(path)==="[object String]"){
    path = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
  }
  return path.length === 1 ? obj[path.shift()] : deepAccess(obj[path.shift()], path);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment