Last active
February 16, 2022 10:29
Naive implementation of lodash.get method
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
/** | |
* @property {object} object - The object to query | |
* @property {string} path - The path of the property to get | |
* @property {object} fallback - The default value to return if no value found in path | |
* @returns {*} Returns the resolved value (undefined / fallback value / value found). | |
*/ | |
function get(object, path, fallback) { | |
const dot = path.indexOf('.'); | |
if (object === undefined) { | |
return fallback || undefined; | |
} | |
if (dot === -1) { | |
if (path.length && path in object) { | |
return object[path]; | |
} | |
return fallback; | |
} | |
return get(object[path.substr(0, dot)], path.substr(dot + 1), fallback); | |
} | |
/* TESTS */ | |
const object = { | |
foo: { | |
bar: 1 | |
}, | |
baz: 5, | |
lor: ['mir', 'dal'] | |
}; | |
console.log(get(object, 'none.bar')); | |
// => undefined | |
console.log(get(object, 'none.bar', 'default')); | |
// => 'default' | |
console.log(get(object, 'baz')); | |
// => 5 | |
console.log(get(object, 'foo.bar')); | |
// => 1 | |
console.log(get(object, 'lor.1')); | |
// => 'dal' |
@fvena-portfolio thanks! I'll fix it right away.
It is an old gist, I use instead a NPM package I created, called getv
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot, great gist, but on line 18 you should return the fallback value as well.