Skip to content

Instantly share code, notes, and snippets.

@sndrs
Last active May 3, 2017 13:43
Show Gist options
  • Save sndrs/3aa410efcf3fe58240981e6a4f93cba1 to your computer and use it in GitHub Desktop.
Save sndrs/3aa410efcf3fe58240981e6a4f93cba1 to your computer and use it in GitHub Desktop.
tiny version of lodash.get https://lodash.com/docs#get
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