
本文介绍如何在 JavaScript 中筛选满足特定条件(如 act === "Q" 且 type === 0)的数组对象,并按指定键(如 line)分组汇总数值字段(如 qty),最终生成结构精简、聚合准确的新数组。
本文介绍如何在 javascript 中筛选满足特定条件(如 `act === "q"` 且 `type === 0`)的数组对象,并按指定键(如 `line`)分组汇总数值字段(如 `qty`),最终生成结构精简、聚合准确的新数组。
要实现从数组对象中按条件筛选 + 分组求和,仅用 filter() 是不够的——它只能筛选出符合条件的元素,但无法完成“按 line 合并并累加 qty”这一聚合操作。正确解法需结合 filter() 与 reduce()(或 Map),以下是推荐的完整实现:
const item = [
{ "act": "Q", "line": 1, "qty": 6, "type": 0 },
{ "act": "Q", "line": 1, "qty": 6, "type": 0 },
{ "act": "Q", "line": 2, "qty": 6, "type": 0 },
{ "act": "Q", "line": 2, "qty": 4, "type": 0 }
];
// 步骤1:筛选 act === "Q" 且 type === 0 的项(注意:type 为数字 0,非字符串 "00")
const filtered = item.filter(obj => obj.act === "Q" && obj.type === 0);
// 步骤2:按 line 分组并累加 qty
const grouped = filtered.reduce((acc, curr) => {
const existing = acc.find(item => item.line === curr.line);
if (existing) {
existing.qty += curr.qty;
} else {
acc.push({ line: curr.line, qty: curr.qty });
}
return acc;
}, []);
console.log(grouped);
// 输出:[{ line: 1, qty: 12 }, { line: 2, qty: 10 }]✅ 关键说明:
-
type: 00在 JavaScript 中等价于type: 0(整数),因此比较时应使用=== 0,而非"00"字符串; - 若数据中
type实际为字符串"00",则条件需改为obj.type === "00"; - 使用
reduce()实现原地聚合,语义清晰、性能良好;也可用Map提升大规模数据下的查找效率:
const map = new Map();
filtered.forEach(({ line, qty }) => {
map.set(line, (map.get(line) || 0) + qty);
});
const result = Array.from(map, ([line, qty]) => ({ line, qty }));? 总结:筛选(filter)与聚合(reduce/Map)需协同使用。避免仅依赖 filter 误以为已达成目标——它只做“减法”,而分组合并是典型的“加法+归约”操作。务必验证原始数据类型(数字 vs 字符串),确保条件判断精准无误。

















