js let list = [{name: '1212', children: null}, {name: '345', children: [{name: '8787', children: null}]}] 递归处理list 删除children为null
时间: 2024-10-25 13:10:08 浏览: 21
在JavaScript中,你可以通过递归函数来遍历这个数组并删除`children`属性值为`null`的对象。这里是一个示例函数:
```javascript
function deleteNullChildren(list) {
// 遍历列表
for (let i = 0; i < list.length; i++) {
// 检查当前元素的children是否为空
if (list[i].children === null) {
// 如果是空,直接移除该元素
list.splice(i, 1);
// 因为splice会改变数组长度,所以需要重新检查i
i--;
} else if (Array.isArray(list[i].children)) {
// 如果children是数组,继续递归处理
deleteNullChildren(list[i].children);
}
}
return list;
}
// 测试用例
let list = [
{ name: '1212', children: null },
{ name: '345', children: [{ name: '8787', children: null }] },
];
let updatedList = deleteNullChildren(list);
console.log(updatedList); // 只保留第一个层级,第二层级的children已删除
```
运行上面的代码后,`updatedList`将只包含第一个层级的对象,因为所有第二层级及以下的节点(children为null的)都已经被删除了。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)