简体   繁体   中英

Checking if a nested object contains only single key-value pair in javascript

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 eg, 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM