我有一个类似 JSON 的 JS 对象层次结构,格式如下:
[
{
subs: [ ...other objects... ]
},
...other objects...
]
我写了一个方法来返回这种层次结构的级别数:
/* Returns the depth of the tree. */
public getDepth(): number {
function f(obj: object): number {
let depth = 0;
if (obj['subs'].length > 0) {
obj['subs'].forEach((s: object) => {
const tempDepth = f(s);
if (tempDepth > depth) depth = tempDepth;
});
}
return depth + 1;
}
if (this.tree.length > 0)
return Math.max(...this.tree.map((s: object) => f(s)));
else return 0;
}
它可以工作,但是太复杂了。然后,我发现了这个更简洁的代码:https://stackoverflow.com/a/16075976/5214911
唯一的区别是我没有一个基础对象,而是一组对象作为根。我怎样才能简化代码以节省额外的 if 和迭代?
示例数据:
const data1 = []; // depth: 0
const data2 = [{}, {}, {}]; // depth: 1
const data3 = [{}, // depth: 5
{
"subs": [{
"subs": [{
"subs": [{}]
}, {
"subs": [{
"subs": [{}]
}]
}]
}, {
"subs": [{
"subs": [{}]
}]
}]
},
{}
];
最佳答案
您可以映射每个 child 的深度并取其最大值。
function getDepth(array) {
return 1 + Math.max(0, ...array.map(({ subs = [] }) => getDepth(subs)));
}
const
data1 = [],
data2 = [{}, {}, {}],
data3 = [{}, { subs: [{ subs: [{ subs: [{}] }, { subs: [{ subs: [{}] }] }] }, { subs: [{ subs: [{}] }] }] }, {}];
console.log(getDepth(data1) - 1); // 0
console.log(getDepth(data2) - 1); // 1
console.log(getDepth(data3) - 1); // 5
关于javascript - 以更简单的方式获取树数据结构的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165017/