Skip to content

Instantly share code, notes, and snippets.

@ItsJonQ
Last active December 1, 2018 23:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ItsJonQ/b6d51ce05ac796d99fcbc1af84ad386c to your computer and use it in GitHub Desktop.
Save ItsJonQ/b6d51ce05ac796d99fcbc1af84ad386c to your computer and use it in GitHub Desktop.
A tiny implementation of lodash.get
/**
* Retrieves a (deeply) nested value from an object.
* A tiny implementation of lodash.get.
*
* Tests:
* https://codesandbox.io/s/48052km1q7
*
* Perf tests:
* https://jsperf.com/get-try-catch-vs-reduce-vs-lodash-get
*
* Created by @itsjonq and @knicklabs
*
* Library:
* https://github.com/ItsJonQ/dash-get
*
* @param {Object} obj Object to retreive value from.
* @param {Array<string>|string} path Key path for the value.
* @param {any} fallback Fallback value, if unsuccessful
* @returns {any} The value, the fallback, or undefined
*/
function get(obj, path, fallback) {
if (!obj || !path) return fallback;
var paths = Array.isArray(path) ? path : path.split(".");
return paths.reduce(function(acc, path) {
if (acc === undefined) return fallback;
var value = acc[path];
return value !== undefined ? value : fallback;
}, obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment