Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active December 14, 2021 19:43
Show Gist options
  • Save Ivannnnn/290ea033bfeba29315a9ade4ea95680e to your computer and use it in GitHub Desktop.
Save Ivannnnn/290ea033bfeba29315a9ade4ea95680e to your computer and use it in GitHub Desktop.
Get object properties by path without error when null
function prop(value, path) {
path = path
.replace(/\[(\d)\]/g, (_, v) => '.' + v)
.replace(/^\./, '')
.split('.')
let current = value
for (let prop of path) {
if (current[prop]) current = current[prop]
else return current[prop]
}
return current
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment