最近有一个需求,有一个数组,数组里面有是一个个的对象,对象里面有可能有一个属性children 这个children是一个数组,里面的对象也很有可能有一个数组,这样不固定,求该数组的最深层级是多少
代码如下:
function getArrayLayer(arr, attr, index = 1) {
let newIndex = index;
for (const iterator of arr) {
let tempIndex = index
if (iterator[attr]) {
tempIndex = getArrayLayer(iterator[attr], attr, index + 1)
if (tempIndex > newIndex) {
newIndex = tempIndex
}
}
}
return newIndex
}
测试:
const arr = [{
child: [{
a: 1,
child: [{
a: 1
},
{
a: 1
}
]
},
{
a: 1
}
]
},
{
a: 1
},
{
a: 1,
child: [{
a: 1,
child: [{
a: 1,
child: [{
a: 1
},
{
a: 1
}
]
},
{
a: 1
}
]
},
{
a: 1
}
]
},
]
console.log(getArrayLayer(arr, 'child'));