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

如何从嵌套对象数组中移除多个对象?现有代码返回undefined求优化

从嵌套对象数组中移除多个对象的优化方案

你的代码本身不会返回undefined,但它存在一个问题:直接修改了原数组中的对象(对象是引用类型,修改副本会影响原数据),可能引发意外的副作用。以下是更优的实现方式:

1. 纯函数实现(不修改原数据)

通过对象解构创建原对象的副本,再替换过滤后的嵌套数组,确保原数据不受影响:

let removedIds = [1, 2];

let gridData = [{
    Id: 1,
    name: "ABC",
    class: "XYZ",
    college: "AB",
    collectionRows: [
        { Id: 1, name: "ABC", class: "XYZ", college: "AB" },
        { Id: 2, name: "ABC", class: "XYZ", college: "AB" },
        { Id: 3, name: "ABC", class: "XYZ", college: "AB" }
    ]
}];

// 纯函数:不修改原数组,返回新的处理后数据
let newData = gridData.map(row => ({
    ...row,
    collectionRows: row.collectionRows.filter(subRow => !removedIds.includes(subRow.Id))
}));

console.log(newData, 'newData');
// 验证原数据未被修改
console.log(gridData[0].collectionRows.length); // 输出 3

2. 优化性能(处理大量数据)

如果removedIds数组元素较多,将其转为Set可以大幅提升查找效率(Set.has()为O(1),Array.includes()为O(n)):

const removedIdSet = new Set(removedIds);
let newData = gridData.map(row => ({
    ...row,
    collectionRows: row.collectionRows.filter(subRow => !removedIdSet.has(subRow.Id))
}));

3. 兼容嵌套数组不存在的情况

如果部分row可能没有collectionRows属性,添加空数组判断避免报错:

let newData = gridData.map(row => ({
    ...row,
    collectionRows: (row.collectionRows || []).filter(subRow => !removedIds.includes(subRow.Id))
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:18:33