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

JavaScript中如何基于多关键词数组过滤JSON对象?

解决数组关键词过滤JSON对象的问题

环境

  • Windows 11
  • VSCode
  • Node.js v18.12.1

需求

使用数组变量作为过滤条件,过滤掉JSON对象中名称包含数组内任意关键词的条目,最终保留名称为Megan和Charlene的对象。

正确实现代码

const carOwners = [
  { "name": "Phil", "age": 52, "car": null },
  { "name": "Carl Phil", "age": 25, "car": "Tesla" },
  { "name": "Bob", "age": 65, "car": "Land Rover" },
  { "name": "Megan", "age": 34, "car": "Mercedez" },
  { "name": "Charlene", "age": 67, "car": "Mazda" }
];

const filteredNames = ['Phil', 'Bob'];

// 过滤逻辑:保留名称不包含任意关键词的对象
const checkUsers = carOwners.filter(user => {
  // 检查当前用户名称是否包含过滤数组中的任意关键词
  const hasKeyword = filteredNames.some(keyword => user.name.includes(keyword));
  // 取反:包含关键词的对象被过滤,不包含的保留
  return !hasKeyword;
});

console.log(checkUsers);

输出结果

[
  { name: 'Megan', age: 34, car: 'Mercedez' },
  { name: 'Charlene', age: 67, car: 'Mazda' }
]

方案说明

核心逻辑是利用Array.prototype.some()遍历过滤关键词数组:

  • some()方法会检查数组中是否存在任意一个元素满足条件(这里是用户名称包含该关键词),只要有一个满足就返回true
  • 对结果取反后,filter()会保留所有不包含任何关键词的对象,完全匹配需求

之前尝试的问题分析

  1. 第一种尝试错误原因:
    user.name.includes(filteredNames)是错误用法,String.prototype.includes()仅接受字符串参数,传入数组会被强制转为"Phil,Bob",而所有用户名称都不包含该子串,导致所有对象都被保留。

  2. 第二种尝试错误原因:
    filteredNames.includes(a.name)是精确匹配,只会过滤名称完全等于"Phil"或"Bob"的对象,而"Carl Phil"不是数组内的精确值,因此被遗漏,不符合"包含关键词"的过滤逻辑。

内容的提问来源于stack exchange,提问作者e-driver1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:20:29