Created
May 23, 2018 16:37
-
-
Save jpitchardu/aeef9e191484ce1815f60123a3ddc5dd to your computer and use it in GitHub Desktop.
Null-safe with regex in javascript
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
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