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

如何在JavaScript中删除嵌套数组对象?请修正我的错误代码

问题修正与优化方案

错误原因

你的代码逻辑有误:外层数组arr的元素是包含demo数组的对象,而你试图通过element.demo?.id查找目标,但demo是数组而非单个对象,因此element.demo?.id始终为undefined,无法匹配到目标元素,自然无法执行删除操作。你需要操作的是嵌套在arr[0]里的demo数组。

修正后的代码(直接修改原数组)

var arr = [
        {
          demo: [
            {
              label: "NOT - Notification",
              id: "NOT",
              subTree: null,
            },
            { 
              label: "LIM - Limitation", 
              id: "LIM", 
              subTree: null 
            },
          ],
    },
];

// 定位demo数组中id为"NOT"的元素索引
const targetIndex = arr[0].demo.findIndex(item => item.id === "NOT");
if (targetIndex !== -1) {
  // 从demo数组中删除目标元素
  arr[0].demo.splice(targetIndex, 1);
}
console.log('this is new', arr);

更优方案(创建新数组,不修改原数据)

如果不需要修改原数组,推荐使用filter结合map的函数式写法,避免副作用:

var arr = [
        {
          demo: [
            {
              label: "NOT - Notification",
              id: "NOT",
              subTree: null,
            },
            { 
              label: "LIM - Limitation", 
              id: "LIM", 
              subTree: null 
            },
          ],
    },
];

// 生成新数组,排除demo中id为"NOT"的元素
const updatedArr = arr.map(obj => ({
  ...obj,
  demo: obj.demo.filter(item => item.id !== "NOT")
}));
console.log('this is new', updatedArr);

方案对比

  • splice方案:直接修改原数组,适合需要原地更新数据的场景
  • filter+map方案:返回新数组,原数据保持不变,更符合现代前端开发的无副作用编程理念

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:15:52