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

如何从嵌套对象数组中过滤深层的null或undefined值?

移除嵌套对象数组深层的undefined值

先看你的示例数组和现有代码,问题出在splice(0, index)的用法上——这个写法会从数组开头删除到当前index位置的元素,反而把有效数据删掉了,留下了原本要移除的undefined。

正确的实现方式

直接用数组的filter方法过滤掉undefined元素,比手动遍历+splice更简洁且不易出错:

partialMatch.forEach(item => {
  // 过滤掉lines数组里的undefined值
  item.lines = item.lines.filter(line => line !== undefined);
});

验证结果

运行后partialMatch会变成:

[
  { lines: [{ id: 1 }, { id: 2 }] },
  { lines: [{ id: 10 }, { id: 25 }] }
]

若一定要用splice的写法

如果坚持用splice,需要倒序遍历数组(从后往前删),因为正序遍历删除元素会改变数组长度,导致后续索引错位:

partialMatch.forEach(item => {
  // 倒序遍历避免索引错位
  for (let i = item.lines.length - 1; i >= 0; i--) {
    if (item.lines[i] === undefined) {
      item.lines.splice(i, 1); // 从索引i的位置删除1个元素
    }
  }
});

但显然filter的写法更直观、可读性更高,优先推荐。

内容的提问来源于stack exchange,提问作者teestunna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:07:10