Skip to content

Instantly share code, notes, and snippets.

@rap0so
Last active January 28, 2021 15:40
Show Gist options
  • Save rap0so/392a6c8bfb8f8ea92baca6bf891e5645 to your computer and use it in GitHub Desktop.
Save rap0so/392a6c8bfb8f8ea92baca6bf891e5645 to your computer and use it in GitHub Desktop.
This function is a improved way of loadash lib
/**
* _Get function is a copy of a method of loadash lib
* that get `property` of `object` testing all nested properties if needs it
*
* @param {object} obj
* @param {string} key
*
*/
function _get(object, keys, defaultVal) {
keys = Array.isArray(keys) ? keys : keys.split('.')
object = object[keys[0]]
if (object && keys.length > 1) {
return _get(object, keys.slice(1), defaultVal)
}
return !object ? defaultVal : object
}
@rap0so
Copy link
Author

rap0so commented May 29, 2020

Why did you cut off the ending curly bracket from the function?

omg mb

ty

@felideo
Copy link

felideo commented Jan 28, 2021

put a try ctach to avoid disorders

``
function _get(object, keys, defaultVal) {
keys = Array.isArray(keys) ? keys : keys.split('.')

try{
	object = object[keys[0]];
}catch(error){
	object = null;
}

if (object && keys.length > 1) {
	return _get(object, keys.slice(1), defaultVal)
}

return !object ? defaultVal : object

}
``

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment