Last active
May 3, 2017 13:43
-
-
Save sndrs/3aa410efcf3fe58240981e6a4f93cba1 to your computer and use it in GitHub Desktop.
tiny version of lodash.get https://lodash.com/docs#get
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
const get = (obj = {}, path = '', defaultValue) => | |
path | |
.replace(/\[(.+?)\]/g, '.$1') | |
.split('.') | |
.reduce((o, key) => o[key], obj) || defaultValue; | |
// PERFORMANCE | |
// It's slower than lodash (surprise surprise), but it's about 97% smaller: | |
// https://jsperf.com/get-object-props/4 | |
// EXAMPLE | |
// const obj = { | |
// a: { b: 'b' } | |
// }; | |
// get(obj, 'a') => { b: 'b' } | |
// get(obj, 'a.b') => 'b' | |
// get(obj, 'a[b]') => 'b' | |
// get(obj, 'asdf') => undefined | |
// get(obj, 'asdf', {}) => {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment