Last active
April 17, 2019 03:19
-
-
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)
This file contains hidden or 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
var target = { | |
foo: { | |
bar: { | |
baz: [ | |
'madness' | |
] | |
} | |
} | |
}; | |
deepAccess(target, 'foo.bar.baz').push('sparta'); | |
console.log(target) //→ {foo:{bar:{baz:['madness', 'sparta']}}} |
This file contains hidden or 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Underscore-less version