Home > other >  Finding out number of occurence of a key in a nested JS object
Finding out number of occurence of a key in a nested JS object

Time:12-24

I have a nested object like

{
name: "John",
parent:{
 parent:{
  parent:{
  }
 }
}
}

Now I want to get the level of the master parent object or basically how many times a parent object has been nested. In this case, I should be getting an output of 3.

CodePudding user response:

You could also do it recursively like this:

const obj = {
name: "John",
parent:{
 parent:{
  parent:{
    parent:{
     parent:{
      parent:{
       }
      }
     }
    }
   }
  }
 }
function findk(o,k,l=0){
  if (o[k]) l=findk(o[k],k,  l)
  return l
}
console.log(findk(obj,"parent"))

CodePudding user response:

You could taken a recursive and iterative approach by checkin the handed over value, if it is an array, then check for wanted key and iterate all values of the array or return zero.

const
    getCount = (object, key) => object && typeof object === 'object'
        ? (key in object)   Object
            .values(object)
            .reduce((s, o) => s   getCount(o, key), 0)
        : 0;
    
    
console.log(getCount({ name: "John", parent: { parent: { parent: {} } } }, 'parent'));

CodePudding user response:

You can do something like this:

const obj = {
name: "John",
parent:{
 parent:{
  parent:{
    parent:{
     parent:{
      parent:{
       }
      }
     }
    }
   }
  }
 }

const keyToTrack = 'parent';
let current = obj[keyToTrack],
     count = 0;

while (typeof current === 'object') {
     current = current[keyToTrack];
     count  = 1;
}

console.log(`The key parent appears ${count} times`)

The base case is when you don't find the key.

CodePudding user response:

let obj = { // treat it like a tree
  name: "John",
  parent: {
    parent: {
      parent: {}
    }
  }
}

const findDepth = (root, key) => {
  let depth = 0;

  let loop = (obj) => {
    if (obj && obj[key]) {
      loop(obj[key]);
      depth  ;
    }
  }
  loop(root);
  return depth;
}

const result = findDepth(obj, 'parent')

console.log(result);

CodePudding user response:

var test = {
  name: "John",
  parent: {
    parent: {
      parent: {}
    }
  }
}

function testObject(object, nestedObject) {
  let i = 0;
  while (true) {
    if (object[nestedObject]) {
      object = object[nestedObject];
      i  ;
    } else {
      return i;
    }
  }
}

console.log(testObject(test, 'parent'));

CodePudding user response:

You can do it by using while like this:

let obj = {
  name: "John",
  parent: {
    parent: {
      parent: {
        parent: {
          parent: {
            parent: {}
          }
        }
      }
    }
  }
};

let key = 'parent', i = 0;
while(obj = obj[key])   i;

console.log(i)

  • Related