You could use OR defaulting to protect against Type Errors, too:
(((obj||{}).prop1||{}).prop2||{}).prop3
Or take this a step further and write a helper for this:
(iterative version)
const getObjPath = (path = []) => obj => { let currentVal = obj; for (const prop of path) { currentValue = (currentVal || {})[ prop ]; if (!currentValue) { return currentValue; } } return currentValue; };
(recursive version)
const getObjPath = ([ prop, ...path ] = []) => (obj = {}) => path.length && obj[prop] ? getObjPath(path)(obj[prop]) : obj[prop];
I typically use the “||” for setting the default values. Thanks for sharing your solution 🙂
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You could use OR defaulting to protect against Type Errors, too:
Or take this a step further and write a helper for this:
(iterative version)
(recursive version)
I typically use the “||” for setting the default values. Thanks for sharing your solution 🙂