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

如何在JavaScript中对对象数组按grade、batch属性进行多属性过滤?

在JavaScript中根据grade和batch过滤JSON数组的方法

嘿,这个需求在JavaScript里其实用Array.prototype.filter()就能轻松搞定,这是处理数组过滤最常用的方法之一。我先给你模拟一组示例数据,再分几种常见场景来演示:

首先假设你的JSON数组解析后长这样:

const studentData = [
  { id: 1, name: "Alice", grade: 10, batch: "A" },
  { id: 2, name: "Bob", grade: 11, batch: "B" },
  { id: 3, name: "Charlie", grade: 10, batch: "A" },
  { id: 4, name: "Diana", grade: 12, batch: "C" },
  { id: 5, name: "Eve", grade: 11, batch: "A" }
];

1. 精确匹配单个grade和batch

如果要找**grade等于10且batch等于"A"**的所有项,直接在filter的回调里用逻辑与(&&)判断两个条件:

const targetGrade = 10;
const targetBatch = "A";

const filteredStudents = studentData.filter(student => {
  return student.grade === targetGrade && student.batch === targetBatch;
});

console.log(filteredStudents);
// 输出结果:[{ id: 1, name: "Alice", grade: 10, batch: "A" }, { id: 3, name: "Charlie", grade: 10, batch: "A" }]

2. 匹配多个可选的grade或batch

比如你需要找**grade是10或11,且batch是"A"**的项,可以用includes()来判断grade是否在允许的列表里:

const allowedGrades = [10, 11];
const targetBatch = "A";

const filteredStudents = studentData.filter(student => {
  return allowedGrades.includes(student.grade) && student.batch === targetBatch;
});

console.log(filteredStudents);
// 输出结果:[{ id: 1, name: "Alice", grade: 10, batch: "A" }, { id: 3, name: "Charlie", grade: 10, batch: "A" }, { id: 5, name: "Eve", grade: 11, batch: "A" }]

3. 模糊匹配batch(比如包含指定关键词)

如果你的batch是类似"A1"、"A2"这种格式,需要匹配batch包含"A"且grade≥10的项,可以用includes()做模糊判断:

const batchKeyword = "A";

const filteredStudents = studentData.filter(student => {
  return student.grade >= 10 && student.batch.includes(batchKeyword);
});

console.log(filteredStudents);
// 输出所有grade≥10且batch含"A"的学生

额外提示

如果你的原始数据是JSON字符串,记得先通过JSON.parse()转换成JavaScript数组再处理:

const rawJson = '[{"id":1,"name":"Alice","grade":10,"batch":"A"},{"id":2,"name":"Bob","grade":11,"batch":"B"}]';
const studentData = JSON.parse(rawJson);
// 之后就可以用上面的过滤逻辑了

另外要注意,filter()方法会返回一个新数组,不会修改原始数据,这能避免意外污染你的源数据~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:18:19