一、场景
场景
有一个树形数据,想要依据每个节点的 disabled 来筛选,失去一个过滤后的新树形数据
二、一般数组(抛砖引玉)
如果只是数组,咱们必定晓得,用 js filter 就能够了
比方:
var arr = [{ name: '小明', disabled: true},
{name: '小白', disabled: false},
{name: '小黑', disabled: true},
]
var newArr = arr.filter(i=> i.disabled)
console.log(newArr)
三、树形数据
那,如果是这样呢?
let treeData = [
{
id: '1',
name: 'AAA',
disabled: false,
children: [
{
id: '1.1',
name: 'BBB',
disabled: false,
children: [
{
id: '1.1.1',
name: 'CCC',
disabled: true,
children: []},
{
id: '1.1.2',
name: 'DDD',
disabled: true,
children: []},
]
},
{
id: '1.2',
name: 'EEE',
disabled: true,
children: []},
]
},
{
id: '2',
name: 'FFF',
disabled: true,
children: [
{
id: '2.1',
name: 'GGG',
disabled: true,
children: [
{
id: '2.1.1',
name: 'HHH',
disabled: false,
children: []},
{
id: '2.1.2',
name: 'III',
disabled: true,
children: []},
]
},
{
id: '2.2',
name: 'JJJ',
disabled: false,
children: []},
{
id: '2.3',
name: 'KKK',
disabled: false,
children: []},
{
id: '2.4',
name: 'LLL',
disabled: true,
children: []},
]
}
]
树形数据的特点就是,你不晓得他有多少层
所以,当遇到树形数据的时候,不必想,必定是 递归
四、定义递归函数
定义一个 递归过滤
的函数
// 定义递归办法,接管一个数组
function deepFilter(list) {
// 应用 filter 过滤以后层的数组
return list.filter(item => {
// filter 其实也是遍历
// 把以后遍历的节点的 children 也调用一次 deepFilter 函数,返回过滤后的数组从新赋值
item.children = deepFilter(item.children)
// 最初判断以后节点是否合乎过滤要求
return item.disabled
})
}
五、残缺示例
舒适提醒
能够间接复制残缺示例看成果哦
let treeData = [
{
id: '1',
name: 'AAA',
disabled: false,
children: [
{
id: '1.1',
name: 'BBB',
disabled: false,
children: [
{
id: '1.1.1',
name: 'CCC',
disabled: true,
children: []},
{
id: '1.1.2',
name: 'DDD',
disabled: true,
children: []},
]
},
{
id: '1.2',
name: 'EEE',
disabled: true,
children: []},
]
},
{
id: '2',
name: 'FFF',
disabled: true,
children: [
{
id: '2.1',
name: 'GGG',
disabled: true,
children: [
{
id: '2.1.1',
name: 'HHH',
disabled: false,
children: []},
{
id: '2.1.2',
name: 'III',
disabled: true,
children: []},
]
},
{
id: '2.2',
name: 'JJJ',
disabled: false,
children: []},
{
id: '2.3',
name: 'KKK',
disabled: false,
children: []},
{
id: '2.4',
name: 'LLL',
disabled: true,
children: []},
]
}
]
// 定义递归办法,接管一个数组
function deepFilter(list) {
// 应用 filter 过滤以后层的数组
return list.filter(item => {
// filter 其实也是遍历
// 把以后遍历的节点的 children 也调用一次 deepFilter 函数,返回过滤后的数组从新赋值
item.children = deepFilter(item.children)
// 最初判断以后节点是否合乎过滤要求
return item.disabled
})
}
// 调用
let newArr = deepFilter(treeData)
// 格式化打印看看成果
console.log(JSON.stringify(newArr, null, 4));