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

如何在JavaScript中使用Reduce实现嵌套数组过滤并修复现有代码

问题分析与修复方案

现有代码错误点

  • 语法错误:JSON.stringify是浏览器/Node.js全局提供的方法,不属于userRecord对象的属性,userRecord.JSON.Stringify的写法完全错误,且你当前作用域下没有定义user变量,直接调用user._id会报引用错误
  • 逻辑错误:merged数组的每一项userRecord是嵌套数组,成员包含两类:带user_id的业务对象、末尾的{user: [Object]}对象,你需要先过滤出带匹配字段的成员再做判断
  • 字段匹配错误:你的匹配目标是user_id字段,现有代码错误取了_id字段,和匹配规则不符

JSON.stringify使用合理性判断

你当前场景下user_id本身就是字符串类型,完全不需要用JSON.stringify处理。只有当你要匹配的字段是MongoDB返回的ObjectId非字符串类型时,才需要用JSON.stringify转成纯字符串再对比,当前场景用了反而会额外添加双引号导致匹配失败。

修复后的可运行代码

const merged = [
  [
    {
      _id: "6136096f4255d84bcb4a7144",
      user_id: "5fbfa729fc46a415ce5503a6",
      device_platform: 'ios',
    },
    { user: [Object] }
  ],
  [
    {
      _id: "613609414255d84bcb4a7122",
      user_id: "5fbf6f91aff7f3320a906547",
      device_platform: 'ios',
    },
    { user: [Object] }
  ],
  [
    {
      _id: "613709f49223350dfdaec618",
      user_id: "5fbfa748fc46a415ce5505f1",
      device_platform: 'ios',
    },
    {
      _id: "613609184255d84bcb4a710a",
      user_id: "5fbfa748fc46a415ce5505f1",
      device_platform: 'ios',
    },
    { user: [Object] }
  ]
]

const user_id = ["5fbfa748fc46a415ce5503a8"];

const { matching, nonMatching } = merged.reduce(
  (acc, userRecord) => {
    // 筛选当前嵌套数组内所有带user_id的对象,判断是否存在匹配项
    const hasMatch = userRecord
      .filter(item => item.user_id) // 过滤掉无关的{user: [Object]}项
      .some(item => user_id.includes(item.user_id));
    
    hasMatch ? acc.matching.push(userRecord) : acc.nonMatching.push(userRecord);
    return acc;
  },
  { matching: [], nonMatching: [] }
);

如果你确实遇到user_id是ObjectId类型的场景,把匹配逻辑改成以下写法即可:

.some(item => user_id.includes(JSON.stringify(item.user_id).replace(/"/g, '')))

特殊场景适配

如果你的匹配规则需要包含{user: [Object]}里的_id字段,调整判断逻辑即可:

const hasMatch = userRecord.some(item => {
  // 匹配普通业务对象的user_id
  if (item.user_id) return user_id.includes(item.user_id);
  // 匹配user对象内的_id
  if (item.user?._id) return user_id.includes(item.user._id.toString());
  return false;
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:15:03