Skip to content

Instantly share code, notes, and snippets.

@svdamani
Last active April 3, 2023 13:17
Show Gist options
  • Save svdamani/e01269239232f89b5d3c5237584e5475 to your computer and use it in GitHub Desktop.
Save svdamani/e01269239232f89b5d3c5237584e5475 to your computer and use it in GitHub Desktop.
Simple JS object safe property accessor function
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