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

前端 未结 6 1708
庸人自扰
庸人自扰 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 15:00

    You could map the depth of every children and take the maximum value of it.

    function getDepth(object) {
        return 1 + Math.max(0, ...(object.children || []).map(getDepth));
    }
    
    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' }] }] }] },
        depth = getDepth(test) - 1; // zero based
    
    console.log(depth);

提交回复
热议问题