DEV Community

Discussion on: Prevent Object Retrieval TypeError with &&

Collapse
 
misterwhat profile image
Jonas Winzen

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];

Collapse
 
samanthaming profile image
Samantha Ming

I typically use the “||” for setting the default values. Thanks for sharing your solution 🙂