Last active
December 14, 2021 19:43
-
-
Save Ivannnnn/290ea033bfeba29315a9ade4ea95680e to your computer and use it in GitHub Desktop.
Get object properties by path without error when null
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 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