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

如何将JS对象数组按user_id匹配key字段拆分为匹配与不匹配两个数组

错误原因

你原代码直接访问users.key是错误的:users是存储多个用户对象的数组,key是单条用户对象的属性,不属于数组本身,因此无法直接读取。

正确实现

可以用以下两种方案实现需求:

方案1:单次遍历拆分(性能更优)

通过Array.reduce仅遍历一次数组即可同时得到匹配、不匹配两个结果集,兼容无key字段的用户记录:

const [match, notMatch] = users.reduce((result, currentUser) => {
  const hasMatch = currentUser.key ? currentUser.key.includes(user_id) : false
  hasMatch ? result[0].push(currentUser) : result[1].push(currentUser)
  return result
}, [[], []])

方案2:筛选法(写法更直观)

通过两次Array.filter分别筛选两个结果集,使用可选链和空值合并运算符简化判断逻辑:

const match = users.filter(user => user.key?.includes(user_id) ?? false)
const notMatch = users.filter(user => !(user.key?.includes(user_id) ?? false))

结果验证

在你给出的示例数据中,最终match数组会包含_id为5fbfa729fc46a415ce5503a6的Allen Border的记录,其余3条记录会归入notMatch数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:12:03