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

JS如何筛选指定属性包含关键词数组中任意字符串的对象数组?

方法原理说明

  • some() 是数组专属方法,用于判断数组中是否存在至少1个元素满足自定义条件,返回布尔值
  • includes() 被字符串调用时,用于判断当前字符串是否包含指定子串,返回布尔值

该需求需要将两个方法结合使用:通过关键词数组调用some()遍历所有关键词,判断对象的name/description是否包含任意一个关键词即可。

完整实现代码

// 定义关键词数组
const keywords = ["ethan", "kathrine"]
// 待筛选的对象数组
const arr = [
  {name: "ethaniel" , description: "strong" , age: 200} ,
  {name: "kathrine" , description: "beautiful" , age: 220},
  {name: "zack" , description: "he loves kathrine" , age: 133},
  {name: "ethan" , description: "he loves kathrine" , age: 133},
  {name: "bob" , description: "he loves trucks" , age: 133}
]

const filteredArr = arr.filter(item => {
  // 校验name是否包含任意关键词
  const nameMatch = keywords.some(keyword => item.name.includes(keyword))
  // 校验description是否包含任意关键词
  const descMatch = keywords.some(keyword => item.description.includes(keyword))
  // 两个字段任意一个匹配成功就保留当前对象
  return nameMatch || descMatch
})

可选优化

如果需要不区分大小写匹配,可以将对比的两个字符串统一转成小写/大写,修改匹配逻辑即可:

const nameMatch = keywords.some(keyword => item.name.toLowerCase().includes(keyword.toLowerCase()))
const descMatch = keywords.some(keyword => item.description.toLowerCase().includes(keyword.toLowerCase()))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:36:02