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

在JavaScript中如何根据对象的数组成员属性筛选对象数组?

实现方案

你可以直接用JavaScript内置的数组方法完成筛选,不需要额外引入工具。核心用到两个方法:

  • filter():遍历原数组,返回所有符合判断条件的元素组成的新数组,不会修改原数组
  • includes():判断数组中是否包含指定元素,返回布尔值

基础筛选代码

const books = [{
  id: "1",
  title: "Book title",
  areas: ["horror", "mystery"]
}, {
  id: "2",
  title: "Book title 2",
  areas: ["friendship", "love", "history"]
},
{
  id: "2",
  title: "Book title 3",
  areas: ["friendship", "scifi"]
}];

// 封装筛选函数,传入要匹配的分类即可得到结果
function getFilteredBooks(targetArea) {
  // 统一转小写匹配,避免大小写差异导致匹配失败,不需要可以删掉转小写的逻辑
  const formatTarget = targetArea.toLowerCase();
  return books.filter(book => 
    book.areas.map(area => area.toLowerCase()).includes(formatTarget)
  );
}

// 调用示例:点击Horror按钮时调用
const filteredBooks = getFilteredBooks("Horror");
console.log(filteredBooks);
// 输出结果:[{id: "1", title: "Book title", areas: ["horror", "mystery"]}]

绑定按钮点击的完整示例

如果需要和页面按钮联动,可参考如下代码:

HTML部分

<button class="tag-btn" data-tag="Horror">Horror</button>
<button class="tag-btn" data-tag="Friendship">Friendship</button>
<button class="tag-btn" data-tag="SciFi">SciFi</button>

JS部分

// 给所有分类按钮绑定点击事件
document.querySelectorAll('.tag-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    // 读取按钮上预设的分类值
    const targetTag = this.dataset.tag;
    // 执行筛选得到结果
    const filteredBooks = getFilteredBooks(targetTag);
    // 拿到结果后可自行处理,比如渲染到页面列表中
    console.log('当前筛选结果:', filteredBooks);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:51:02