W3docs

How to Check for the Existence of Nested JavaScript Object Key

In this tutorial, you will find several methods that are used to test the existence of the nested JavaScript object keys. Also, find how to avoid TypeError.

To check for the existence of a property in nested objects, you should do it step by step to avoid a TypeError. It will be thrown if at least one member is null or undefined and you try to access a property on it.

There are two ways to avoid it. Either you can catch the exception using a try-catch block, or create a function to test the existence of multiple levels like this:

Check for the existence of nested javascript object key

javascript— editable

Using ES6 features can make the function even shorter:

Check for the existence of nested javascript object key

function checkNested(obj, level, ...rest) {
  if (obj == null) return false;
  if (rest.length == 0 && obj.hasOwnProperty(level)) return true;
  return checkNested(obj[level], ...rest);
}

To get the nested property value and also check its existence, use the following one-liner:

Get the nested property value and also check javascript

javascript— editable

You can also use the optional chaining operator to access deeply nested properties, by using the token ?.:

Check for the existence of nested javascript object key

const value = obj?.level1?.level2?.level3;

If any of the accessed levels is null or undefined, the expression will resolve to undefined.

The operator also handles method calls safely:

Check for the existence of nested javascript object key

obj?.level1?.method?.();

The above expression produces undefined if obj, obj.level1, or obj.level1.method are null or undefined; otherwise, it will call the function.

The optional chaining operator

The optional chaining operator (?.) is a standard feature in ES2020. It permits reading the value of a property that is located deep in a chain of connected objects without having to expressly validate that each reference is valid. The ?. operator allows it to short-circuit if a reference evaluates to null or undefined. When used with function calls, it returns undefined if the function does not exist.