Last active
December 1, 2018 23:46
-
-
Save ItsJonQ/b6d51ce05ac796d99fcbc1af84ad386c to your computer and use it in GitHub Desktop.
A tiny implementation of lodash.get
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
/** | |
* 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