Skip to content

Instantly share code, notes, and snippets.

@jpitchardu
Created May 23, 2018 16:37
Show Gist options
  • Save jpitchardu/29bca24501838a5a25133bb19115980e to your computer and use it in GitHub Desktop.
Save jpitchardu/29bca24501838a5a25133bb19115980e to your computer and use it in GitHub Desktop.
Null-safe with regex in javascript
function optionalAccess(obj, path, def) {
const propNames = path.replace(/\]|\)/, "").split(/\.|\[|\(/);
return propNames.reduce((acc, prop) => acc[prop] || def, obj);
}
const obj = {
items: [
{ hello: "Hello" }
]
};
console.log(optionalAccess(obj, "items[0].hello", "def")); // => Hello
console.log(optionalAccess(obj, "items[0].he", "def")); // => def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment