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

JavaScript中过滤id为整数的对象数组实现模糊匹配

问题原因

includes是仅存在于String、Array原型上的方法,你要过滤的id字段为整数类型,直接调用该方法自然会抛出includes is not a function错误。

解决方法

只要在判断前将整数类型的id转为字符串,同时为了避免过滤值也是整数类型导致匹配异常,建议同步将过滤值也转为字符串再做匹配即可,代码示例如下:

const filterVal = 12
const arr = [{id:123, name:'xyz'}, {id:122, name:'xyy'}, {id:134, name:'zzz'}]

const filteredArr = arr.filter(item => {
  return String(item.id).includes(String(filterVal))
})

执行后filteredArr的输出就是你期望的结果:

[{id:123, name:'xyz'}, {id:122, name:'xyy'}]

额外说明

如果你后续需要改为全值匹配而非模糊匹配,不需要转字符串,直接用全等判断即可:

const filteredArr = arr.filter(item => item.id === filterVal)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:36:04