如何按lineId和totalTime筛选重复对象并生成新数组
按条件筛选数组:保留同一lineId的totalTime总和超744的去重对象
需求说明
从API获取响应数据后,需按以下规则创建新数组:
- 对每个
lineId,计算其所有对应对象的totalTime总和 - 若总和超过744,将该
lineId对应的单个对象(去重后)加入新数组
API响应数据
const response = [ { "lineId": "333", "oeeCalculations": { "others": { "totalTime": 744 } } }, { "lineId": "333", "oeeCalculations": { "others": { "totalTime": 744 } } }, { "lineId": "111", "oeeCalculations": { "others": { "totalTime": 744 } } }, { "lineId": "111", "oeeCalculations": { "others": { "totalTime": 744 } } }, { "lineId": "1115", "oeeCalculations": { "others": { "totalTime": 200 } } } ];
预期输出
const result = [ { "lineId": "333", "oeeCalculations": { "others": { "totalTime": 744 } } }, { "lineId": "111", "oeeCalculations": { "others": { "totalTime": 744 } } } ];
问题代码
我尝试了以下代码,但无法正确计算totalTime总和,未达到预期效果:
const foundDuplicateName = response.find((nnn, index) => { return response.find((x, ind) => x.lineId === nnn.lineId && x.oeeCalculations.others.totalTime >= 744 && nnn.oeeCalculations.others.totalTime >= 744 && index !== ind) }) console.log(foundDuplicateName)
解决方案
原代码仅通过find查找重复项,未计算totalTime总和,也无法批量处理所有符合条件的lineId。正确做法是先统计每个lineId的总时长,再筛选符合条件的对象:
// 统计每个lineId的总时长,同时保存对应对象(去重) const lineStats = response.reduce((acc, item) => { const lineId = item.lineId; if (!acc[lineId]) { acc[lineId] = { total: item.oeeCalculations.others.totalTime, data: item }; } else { acc[lineId].total += item.oeeCalculations.others.totalTime; } return acc; }, {}); // 筛选总时长超过744的对象,组成结果数组 const result = Object.values(lineStats) .filter(stat => stat.total > 744) .map(stat => stat.data); console.log(result);
代码说明
- 统计阶段:使用
reduce遍历原数组,以lineId为键,累计每个lineId的totalTime总和,同时保存第一个遇到的对象(自动去重)。 - 筛选阶段:将统计结果的取值提取为数组,过滤出总时长超过744的项,再提取对应的对象,得到最终符合要求的数组。
内容的提问来源于stack exchange,提问作者Tinku Tiwari
相关产品推荐
相关产品推荐

