如何基于lineId和status从对象数组中移除重复对象
问题:移除数组中重复对象,保留指定状态项
我有一个response数组,需要基于lineId和status移除重复对象:当同一个lineId对应多个对象时,移除其中status为New的对象;如果lineId只对应一个对象,无论status是什么都保留。我尝试了一段代码,但没得到预期结果,求帮忙。
原始数组
const response = [ { "line": "Line 2", "lineId": "R_X002_WC02", "status": "New" }, { "line": "Line 3", "lineId": "R_X002_WC03", "status": "New" }, { "line": "Line 2", "lineId": "R_X002_WC02", "status": "Submitted" }, { "line": "Line 4", "lineId": "R_X002_WC04", "status": "New" }, { "line": "Line 4", "lineId": "R_X002_WC04", "status": "Submitted" } ];
预期输出
const ExpectedOutput = [ { "line": "Line 3", "lineId": "R_X002_WC03", "status": "New" }, { "line": "Line 2", "lineId": "R_X002_WC02", "status": "Submitted" }, { "line": "Line 4", "lineId": "R_X002_WC04", "status": "Submitted" } ];
我尝试的代码
var finalarr = []; response.forEach((item) => { response.filter(i => i.lineId === item.lineId).length > 1 finalarr.push(item); });
解决方案
你的代码问题在于:判断语句仅执行但未用来控制元素推入逻辑,所有元素都被保留,完全没起到过滤作用。
正确思路是先统计每个lineId的出现次数,再结合次数和status进行过滤:
// 统计每个lineId的出现次数 const lineIdCounter = response.reduce((countMap, current) => { countMap[current.lineId] = (countMap[current.lineId] || 0) + 1; return countMap; }, {}); // 过滤数组得到结果 const finalArr = response.filter(item => { // 两种情况保留:lineId只出现一次,或者lineId多次出现但status不是New return lineIdCounter[item.lineId] === 1 || item.status !== 'New'; }); console.log(finalArr); // 输出与预期一致
代码解释
- 统计次数:用
reduce遍历数组,生成以lineId为键、出现次数为值的映射对象,快速获取每个lineId的对应项数量; - 过滤逻辑:遍历数组时,对每个元素:
- 若
lineId仅出现一次,直接保留; - 若
lineId出现多次,仅保留status不为New的元素。
- 若
此逻辑可精准移除重复lineId下的New状态对象,得到预期结果。
内容的提问来源于stack exchange,提问作者Shilpa
相关产品推荐
相关产品推荐

