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

如何从对象数组中筛选并按line字段汇总qty数值

筛选数组并按指定字段分组汇总数值

需求说明

从给定的JavaScript对象数组中,筛选出act字段为"Q"且type字段为00的项,按line字段分组并汇总对应qty字段的数值,最终输出包含line和对应qty总和的对象数组。

示例输入数据

const item = [
    { "act": "Q", "line": 1, "qty": 6, "type": "00" },
    { "act": "Q", "line": 1, "qty": 6, "type": "00" },
    { "act": "Q", "line": 2, "qty": 6, "type": "00" },
    { "act": "Q", "line": 2, "qty": 4, "type": "00" }
];

注意:示例中type字段的00建议写成字符串形式,避免被JS自动解析为数字0

实现代码

// 1. 筛选符合条件的项
const filteredItems = item.filter(item => item.act === "Q" && item.type === "00");

// 2. 按line分组并累加qty
const groupedData = filteredItems.reduce((acc, curr) => {
    // 若当前line未在分组中,初始化分组项
    if (!acc[curr.line]) {
        acc[curr.line] = { line: curr.line, qty: 0 };
    }
    // 累加当前项的qty
    acc[curr.line].qty += curr.qty;
    return acc;
}, {});

// 3. 将分组对象转换为目标数组格式
const result = Object.values(groupedData);

console.log(result);

输出结果

[
    { "line": 1, "qty": 12 },
    { "line": 2, "qty": 10 }
]

代码说明

  • filter方法:先过滤出符合act="Q"且type="00"的元素,确保后续只处理目标数据
  • reduce方法:通过临时对象存储分组信息,以line值为键,逐步累加对应qty的总和
  • Object.values:提取临时对象中的所有分组项,转换为需求要求的数组格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:05:01