[英]How can I check how many levels deep an object is nested?
Say I have the following object:假设我有以下对象:
const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3
}
]
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
}
]
}
]
}
]
},
]
}
How can I tell how deep the object goes?如何判断物体的深度? For example the above object would be 4 levels deep.
例如,上面的对象将有 4 层深。
I've searched SO and the only thing similar I could find was this question , but it did not work for me, and also seems very outdated.我已经搜索过 SO,我能找到的唯一类似的东西是这个问题,但它对我不起作用,而且似乎已经过时了。
Found an answer for this.为此找到了答案。 In case anyone comes across this in the future:
万一有人在未来遇到这个:
const myObj={id:1,children:[{id:2,children:[{id:3}]},{id:4,children:[{id:5,children:[{id:6,children:[{id:7,}]}]}]},]} function determineDepthOfObject(object) { let depth = 0; if (object.children) { object.children.forEach(x => { let temp = this.determineDepthOfObject(x); if (temp > depth) { depth = temp; } }) } return depth + 1; } console.log(determineDepthOfObject(myObj))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.