Last active
April 3, 2023 13:17
-
-
Save svdamani/e01269239232f89b5d3c5237584e5475 to your computer and use it in GitHub Desktop.
Simple JS object safe property accessor function
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
function safeGet(obj, props, defaultValue) { | |
if (typeof props === 'string') { | |
props = props.split('.'); | |
} | |
function safeGetByArray(obj, propsArray, defaultValue) { | |
if (obj === undefined || obj === null) { | |
return defaultValue; | |
} | |
if (propsArray.length === 0) { | |
return obj; | |
} | |
return safeGetByArray( | |
obj[propsArray[0]], | |
propsArray.slice(1), | |
defaultValue | |
); | |
} | |
return safeGetByArray(obj, props, defaultValue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment