How do I write this recursive function to find the max depth of my object?

前端 未结 6 1694
庸人自扰
庸人自扰 2020-12-06 14:30

I\'m trying to write a function that will loop through my object and return the level depth of the object.

For example, if I ran the function on this object:

6条回答
  •  独厮守ぢ
    2020-12-06 14:57

    Here's a proposal:

    function depth(o){
      var values;
      if (Array.isArray(o)) values = o;
      else if (typeof o === "object") values = Object.keys(o).map(k=>o[k]);
      return values ? Math.max.apply(0, values.map(depth))+1 : 1;
    }
    

    var test = {
      name: 'item 1',
      children: [{
        name: 'level 1 item',
        children: [{
          name: 'level 2 item'
        },
        {
          name: 'second level 2 item',
          children: [{
            name: 'level 3 item'
          }]
        }]
      }]
    };
    
    function depth(o){
      var values;
      if (Array.isArray(o)) values = o;
      else if (typeof o === "object") values = Object.keys(o).map(k=>o[k]);
      return values ? Math.max.apply(0, values.map(v=>depth(v)))+1 : 1;
    }
    
    console.log(depth(test))

    EDIT: this is a generic solution. I'm still unsure whether you wanted a very specific one (i.e. with a children field or a generic one).

提交回复
热议问题