/**
* items 要遍历的数组
* childrenNodeName 子节点名称
* 执行后会直接更改原数组
*/
function recursiveFunction(items, childrenNodeName) {
// 获取数组长度
let len = items.length
// 循环遍历数组
for (let i = 0; i < len; i++) {
// 如果有子节点,递归遍历子节点
if (items[i][childrenNodeName].length > 0) {
recursiveFunction(items[i][childrenNodeName], childrenNodeName)
}
// 删除不满足某些条件的节点,删除后,当前数组下标、长度均减一(这里条件是:类型非技术,且没有子节点的)
if (items[i].type !== '技术' && items[i][childrenNodeName].length === 0) {
items.splice(i, 1)
len--
i--
}
}
}
// 举例(只有两层,多层也可以)
let items = [
{
name: '公司01',
type: '技术',
department: [
{ name: '公司01-部门01', type: '技术', department: [] },
{ name: '公司01-部门02', type: '销售', department: [] },
{ name: '公司01-部门03', type: '销售', department: [] }
]
},
{
name: '公司02',
type: '销售',
department: [
{ name: '公司02-部门01', type: '销售', department: [] },
{ name: '公司02-部门02', type: '销售', department: [] },
{ name: '公司02-部门03', type: '技术', department: [] }
]
},
{
name: '公司03',
type: '销售',
department: [
{ name: '公司03-部门01', type: '销售', department: [] },
{ name: '公司03-部门02', type: '销售', department: [] },
{ name: '公司03-部门03', type: '销售', department: [] }
]
}
]
recursiveFunction(items, 'department')
// 执行后的items的值为:
[
{
name: '公司01',
type: '技术',
department: [
{ name: '公司01-部门01', type: '技术', department: [] }
]
},
{
name: '公司02',
type: '销售',
department: [
{ name: '公司02-部门03', type: '技术', department: [] }
]
}
]
05-06
258
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)