Test for existence of nested JavaScript object key

General Tech QA/Testing 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on QA/Testing related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

If I have a reference to an s://forum.tuteehub.com/tag/object">object:

var test = {};

that will potentially (but not is://forum.tuteehub.com/tag/m">ms://forum.tuteehub.com/tag/m">mediately) have nested s://forum.tuteehub.com/tag/s://forum.tuteehub.com/tag/object">objects">s://forum.tuteehub.com/tag/object">objects, sos://forum.tuteehub.com/tag/m">mething like:

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

What is the s://forum.tuteehub.com/tag/best">best way to test for the existence of keys in the s://forum.tuteehub.com/tag/m">most deeply nested s://forum.tuteehub.com/tag/s://forum.tuteehub.com/tag/object">objects">s://forum.tuteehub.com/tag/object">objects?

alert(test.level1); yields undefined, but alert(test.level1.level2.level3); fails.

I’s://forum.tuteehub.com/tag/m">m currently doing sos://forum.tuteehub.com/tag/m">mething like this:

if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
}

but I was wondering if there’s a better way.

profilepic.png
manpreet 2 years ago

 

+500

You have to do it step by step if you don't want a TypeError, because if one of the members is nullor undefined, and you try to access a member an exception will be thrown.

You can either simply catch the exception, or make a function to test the existence of multiple levels, something like this:

function checkNested(obj /*, level1, level2, ... levelN*/) {
  var 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;
}

var test = {level1:{level2:{level3:'level3'}} };

checkNested(test, 'level1', 'level2', 'level3'); // true
checkNested(test, 'level1', 'level2', 'foo'); // false

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.