Test for existence of nested JavaScript object key in JavaScript


Suppose, we have a reference to an object −

let test = {};

This object will potentially (but not immediately) have nested objects, something like −

test = {level1: {level2: {level3: "level3"}}};

We are required to write a JavaScript function that takes in one such object as the first argument and then any number of key strings as the arguments after.

The function should determine whether or not the nested combination depicted by key strings exist in the object.

Example

The code for this will be −

const checkNested = function(obj = {}){
   const args = Array.prototype.slice.call(arguments, 1);
   for (let 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'));
console.log(checkNested(test, 'level1', 'level2', 'foo'));

Output

And the output in the console will be −

true
false

Updated on: 24-Nov-2020

689 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements