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
相关产品推荐
相关产品推荐

