How to Check for the Existence of Nested JavaScript Object Key

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

There are two ways of avoiding it. Either you can catch the exception or make a function to test the existence of multiple levels like this:

Check for the existence of nested javascript object key
function checkNested(obj /*, level1, level2, ... levelN*/ ) { let args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { if (!obj || !obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; } return true; } let test = { level1: { level2: { level3: 'level3' } } }; console.log(checkNested(test, 'level1', 'level2', 'level3')); // true console.log(checkNested(test, 'level1', 'level2', 'foo')); // false

Using ES6 features can make the function even shorter:

function checkNested(obj, level, ...rest) {
  if (obj === undefined) 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
function getNested(obj, ...args) { return args.reduce((obj, level) => obj && obj[level], obj) } const test = { level1: { level2: { level3: 'level3' } } }; console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3' console.log(getNested(test, 'level1', 'level2', 'level3', 'length')); // 6 console.log(getNested(test, 'level1', 'level2', 'foo')); // undefined console.log(getNested(test, 'a', 'b')); // undefined

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

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

If any of the given levels accessed is null or undefined the expression will resolve to undefined by default.

The operator also handles method calls safely:

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 proposal and 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 functions the allows to short-circuits if a reference evaluates to null or undefined. When used with function calls, it returns undefined in case the function does not exist.