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

如何通过子值数组过滤对象数组?

用值数组过滤对象数组的解决方案

嘿,我完全懂你的困扰——单个过滤字符串的时候很顺手,但换成数组就卡壳了对吧?其实只要把「单个值匹配」改成「数组包含检查」就行,下面给你几个实用的实现方法:

基础场景:匹配对象的单个属性值

假设你有一组对象,每个对象有个明确的属性(比如category),你想用一个值数组来筛选出属性值在数组里的对象,用Array.filter() + Array.includes()就能轻松搞定:

示例代码

// 你的目标对象数组
const products = [
  { id: 1, name: "无线耳机", category: "数码" },
  { id: 2, name: "悬疑小说", category: "图书" },
  { id: 3, name: "机械键盘", category: "数码" },
  { id: 4, name: "烘焙食谱", category: "生活" }
];

// 你的过滤值数组
const targetCategories = ["数码", "图书"];

// 执行过滤
const filteredProducts = products.filter(product => 
  targetCategories.includes(product.category)
);

console.log(filteredProducts);
// 输出:包含id1、id2、id3的对象数组

逻辑说明

  • filter()会遍历目标数组的每个对象,只保留返回true的元素
  • includes()检查当前对象的category值是否存在于targetCategories数组中,存在就返回true

进阶场景:匹配对象的子数组属性

如果你的对象里有一个子数组属性(比如tags标签数组),想要筛选出子数组中包含过滤数组任意值的对象,可以用Array.some()配合includes():

示例代码

const products = [
  { id: 1, name: "无线耳机", tags: ["数码", "便携", "降噪"] },
  { id: 2, name: "悬疑小说", tags: ["图书", "悬疑", "畅销"] },
  { id: 3, name: "机械键盘", tags: ["数码", "电竞", "有线"] },
  { id: 4, name: "烘焙食谱", tags: ["生活", "美食", "入门"] }
];

const targetTags = ["便携", "电竞"];

const filteredProducts = products.filter(product => 
  // 检查当前对象的tags数组是否有至少一个元素在目标数组里
  product.tags.some(tag => targetTags.includes(tag))
);

console.log(filteredProducts);
// 输出:包含id1、id3的对象数组

额外优化:处理大小写敏感问题

如果你的过滤值和对象属性值存在大小写不一致的情况,可以统一转成小写(或大写)再匹配:

// 先把过滤数组统一转小写
const targetCategories = ["数码", "图书"].map(item => item.toLowerCase());

const filteredProducts = products.filter(product => 
  targetCategories.includes(product.category.toLowerCase())
);

这样不管是"数码"还是"SHUMA"都能正确匹配啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:15:06