我们经常会遇到后台返回数据是一个数组,但是我们需要渲染到页面上的数据却是层层嵌套的,比如这种列表:
很明显一个数组是做不到了,那么我们可以使用递归来解决
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let arr = [{
id: 'a1',
pid: '',
name: '飞机'
}, {
id: 'a2',
pid: '',
name: '汽车'
}, {
id: 'a3',
pid: 'a2',
name: '宝马'
}, {
id: 'a4',
pid: 'a2',
name: '奥迪'
}, {
id: 'a5',
pid: '',
name: '船'
}, {
id: 'a6',
pid: 'a5',
name: '快艇'
}]
//递归
// 定义封装函数
function toDo(arr, pid = '') {
// 得到处理之后的树形数据
let newArr = []
// 1.循环数组
arr.forEach(item => {
if (item.pid === pid) {
// 3.收集不是第一层的
let child = toDo(arr, item.id)
if (child.length) {
item.children = child
}
// 2.筛选第二层
newArr.push(item)
}
})
return newArr
}
console.log(toDo(arr));
</script>
</body>
</html>
控制台打印结果:
展开
这样我们就得到一个可以无限嵌套的树形数据啦!如果对你有用的话可以点赞~