0

I want to check if a deeply nested object consists of single key-value pair, if it does, it should return true else false.

For e.g., I want the below code to return true,

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

And the below code to return false,

var test2 = {
                level1: {
                  level2: {'a': '1', 'b': 2},
                  level3: {'a': '2', 'c': 4}
                }
            };

Also, the below code should return true,

var test3 = 
{
  level1: {
    level2: {
      level3: {
        level4: {
          1: "1",
          2: "2",
          3: "3",
          4: "4"
        }
      }
    }
  }
}

I made the following program for it, but it doesn't work,

function checkNested(obj) {
  if(typeof(obj) === 'object') {
    if(Object.keys(obj).length === 1) {
      var key = Object.keys(obj);
      checkNested(obj[key])
    } else { 
      return(false);
    }
  }
  return(true);
}

Could someone please suggest me how can I achieve it?

1 Answer 1

4

With var key = Object.keys(obj);, key becomes an array (containing the one key), so obj[key] doesn't make sense. You might destructure the [key] instead:

const [key] = Object.keys(obj);
return checkNested(obj[key])

(make sure to return the recursive call)

Or, even better, use Object.values, since you don't actually care about the keys:

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

var test2 = {
  level1: {
    level2: 'level2',
    level3: 'level3'
  }
};

function checkNested(obj) {
  if (typeof(obj) === 'object') {
    const values = Object.values(obj);
    if (values.length !== 1) {
      return false;
    }
    return checkNested(values[0]);
  }
  return true;
}

console.log(checkNested(test));
console.log(checkNested(test2));

Sign up to request clarification or add additional context in comments.

10 Comments

Your code is returning false for the below code, var test3 = { level1: { level2: { level3: { level4: { 1: "1", 2: "2", 3: "3", 4: "4" } } } } }
Yep, because it has more than one nested key-value pair.
Hi, I updated my question, I want the code to return true even for test3
It does return false for test3. (as your first comment noted)
My bad, I want it to return true even in such cases as test3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.