如何从对象数组中筛选并按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
相关产品推荐
相关产品推荐

