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

如何通过关联数组的refund字段过滤嵌套数组的子数组?

解决方案

步骤1:构建高效的退款状态映射

先把array2转换成以id为键的对象,后续查找产品退款状态时无需反复遍历数组,大幅提升匹配效率:

const refundMap = array2.reduce((map, item) => {
  map[item.id] = item.refund;
  return map;
}, {});

步骤2:过滤array1并处理嵌套products数组

遍历array1,对每个对象的products数组筛选出退款状态为true的元素,最后剔除筛选后products为空的对象:

const filteredArray1 = array1.map(item => {
  // 筛选当前对象中符合退款条件的products
  const filteredProducts = item.products.filter(product => refundMap[product.id] === true);
  // 返回包含筛选后products的新对象(不修改原数据)
  return { ...item, products: filteredProducts };
}).filter(item => item.products.length > 0); // 只保留products不为空的对象

完整可运行代码

const array1 = [
    {
        name: "this is name1",
        products: [
            { id: "4" },
            { id: "2" },
        ]
    },
    {
        name: "this is name2",
        products: [
            { id: "2" },
            { id: "1" }
        ]
    }
]

const array2 = [
    { id: "1", refund: true },
    { id: "2", refund: false },
    { id: "3", refund: true },
    { id: "4", refund: false}
]

// 构建退款状态映射表
const refundMap = array2.reduce((map, item) => {
  map[item.id] = item.refund;
  return map;
}, {});

// 执行过滤逻辑
const filteredArray1 = array1.map(item => {
  const filteredProducts = item.products.filter(product => refundMap[product.id] === true);
  return { ...item, products: filteredProducts };
}).filter(item => item.products.length > 0);

console.log(filteredArray1);

输出结果验证

运行代码后,输出与预期完全一致:

[
    {
        name: "this is name2",
        products: [
            { id: "1" }
        ]
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:42:08