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?

asked Jan 21, 2019 at 9:51

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));

answered Jan 21, 2019 at 9:54
10
  • Your code is returning false for the below code, var test3 = { level1: { level2: { level3: { level4: { 1: "1", 2: "2", 3: "3", 4: "4" } } } } } Commented Jan 21, 2019 at 10:01
  • 2
    Yep, because it has more than one nested key-value pair. Commented Jan 21, 2019 at 10:02
  • Hi, I updated my question, I want the code to return true even for test3 Commented Jan 21, 2019 at 10:05
  • It does return false for test3. (as your first comment noted) Commented Jan 21, 2019 at 10:06
  • My bad, I want it to return true even in such cases as test3 Commented Jan 21, 2019 at 10:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.