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

如何编写递归函数,根据ID过滤含父子结构的对象数组?

过滤对象数组:移除指定ID的父元素或子元素

需求说明:给定一个包含父对象的数组,每个父对象包含_id字段和assets子数组(子元素同样带有_id),需实现以下过滤逻辑:

  • 若父元素的_id匹配目标ID,直接移除该父元素
  • 若子元素的_id匹配目标ID,仅移除该子元素,保留父元素及其他子元素

待过滤数组:

const arrayToBeFiltered = [
  {
    _id: "1",
    assets: [
      { _id: "2" },
      { _id: "3" },
    ],
  },
  {
    _id: "4",
    assets: [
      { _id: "5" },
    ],
  },
];

实现代码

function filterArrayByTargetId(arr, targetId) {
  // 先过滤匹配ID的父元素,再处理剩余元素的子数组
  return arr
    .filter(parent => parent._id !== targetId)
    .map(parent => ({
      ...parent,
      assets: parent.assets.filter(child => child._id !== targetId)
    }));
}

逻辑说明

  1. 过滤父元素:使用Array.filter直接排除所有_id等于目标ID的父对象
  2. 过滤子元素:对剩余的父对象,通过展开运算符(...)创建新对象(避免修改原数组),同时对assets数组执行过滤,移除_id匹配的子元素

示例验证

示例1:传入ID为"3"

const result1 = filterArrayByTargetId(arrayToBeFiltered, "3");
console.log(result1);

输出:

[
  {
    _id: "1",
    assets: [{ _id: "2" }],
  },
  {
    _id: "4",
    assets: [{ _id: "5" }],
  },
];

示例2:传入ID为"4"

const result2 = filterArrayByTargetId(arrayToBeFiltered, "4");
console.log(result2);

输出:

[
  {
    _id: "1",
    assets: [{ _id: "2" }, { _id: "3" }],
  },
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:36:14