javascript - 如何检查对象嵌套了多少层?
问题描述
假设我有以下对象:
const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3
}
]
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
}
]
}
]
}
]
},
]
}
如何判断物体的深度?例如,上面的对象将是 4 层深。
我已经搜索过,唯一能找到的类似问题是这个问题,但它对我不起作用,而且似乎也很过时。
解决方案
找到了答案。如果将来有人遇到这种情况:
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))
推荐阅读
- leaflet - 如何将 geoman-io 与 ngx-leaflet 一起使用
- sql - 通过 SQL 嵌套引用检查逻辑约束
- pentaho - 增量 - Pentaho 数据集成 (PDI)
- python - 为双参数函数(点数据云)构建网格并使用 Python 将其保存为 .ply 文件
- vba - VBA-如何防止我的按钮在运行代码后自行删除?
- javascript - iOS 上的 Appium 自动授予权限
- android - 在请求期间改造更改字符串字符
- jquery - 如何在 android 设备上使引导模式可拖动和可滚动
- tensorflow - Tensorflow - 解释 tf.estimator.ProfilerHook "_Send" op
- c - 尝试分配二维数组时出错,然后使用它们