You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除嵌套数组中的null对象?

移除嵌套数组中所有null元素的正确实现方法

需求说明

需要处理多层嵌套的对象数组,移除所有层级children数组中的null元素。

错误分析

你之前的递归函数存在两个核心问题:

  1. deactiveRecursive仅处理了当前层级的children过滤,没有递归遍历子元素的children,导致深层嵌套的null无法被移除;
  2. removeRecursive存在拼写错误(chidlren应为children),且filter的回调逻辑错误——filter要求返回布尔值,而非对象,因此无法正确过滤元素。

正确实现方案

方案一:递归遍历处理

通过递归遍历所有层级的对象和数组,逐层过滤null并处理子元素:

function removeNullChildren(item) {
  // 直接返回null,后续过滤时会被剔除
  if (item === null) return null;
  // 非对象类型直接返回原数据
  if (typeof item !== 'object') return item;

  // 处理数组:先过滤null,再递归处理每个元素
  if (Array.isArray(item)) {
    return item.filter(child => child !== null).map(removeNullChildren);
  }

  // 处理对象:复制原对象,递归处理children属性
  const cleanedObj = { ...item };
  if (cleanedObj.children) {
    cleanedObj.children = removeNullChildren(cleanedObj.children);
  }
  return cleanedObj;
}

// 使用示例
const cleanedArray = removeNullChildren(obj);

方案二:利用JSON序列化改进(基于你之前的思路)

改进你用过的JSON.stringify方法,在遍历过程中直接过滤数组中的null:

const cleanedArray = JSON.parse(JSON.stringify(obj, (key, value) => {
  // 遇到数组时过滤掉所有null元素
  if (Array.isArray(value)) {
    return value.filter(item => item !== null);
  }
  return value;
}));

这个方法利用JSON.stringify的遍历特性,自动处理所有嵌套层级的数组,无需手动写递归逻辑,代码更简洁。

内容的提问来源于stack exchange,提问作者Nilton Schumacher F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:27:47