深度检查并移除数组重复对象:基于offerId实现数组去重
基于offerId实现数组对象去重的解决方案
嘿,我来帮你搞定这个数组去重的需求!你需要根据嵌套在对象里的offerId来过滤数组,保证最终数组里每个offerId只出现一次,对吧?下面给你两种常用的JavaScript实现方案,你可以根据需求选择:
方案一:保留第一个出现的对象(使用filter + Set)
这个方法会遍历数组,只保留每个offerId第一次出现的对象,后续重复的都会被过滤掉,代码简洁高效:
const originalArray = [ { actionType: 10, orderItemId: "3205ae52-ab00-4823-a004-da0cda639065", productComponentAction:{ productComponent:{ offerId: 10002839, parentOfferId: 10003058, adoptableProdCompId: undefined } } }, { actionType: 10, orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae", productComponentAction:{ productComponent:{ offerId: 10002839, parentOfferId: 10003058, adoptableProdCompId: undefined } } } ]; // 创建Set来记录已经见过的offerId const seenOfferIds = new Set(); // 过滤数组,只保留未出现过的offerId对应的对象 const uniqueArray = originalArray.filter(item => { const offerId = item.productComponentAction.productComponent.offerId; // 如果offerId不在Set中,就添加进去并保留当前对象 if (!seenOfferIds.has(offerId)) { seenOfferIds.add(offerId); return true; } // 否则过滤掉 return false; }); console.log(uniqueArray);
方案二:保留最后一个出现的对象(使用reduce + Map)
如果你想保留每个offerId最后一次出现的对象,可以用reduce结合Map来实现,它会覆盖之前存储的同offerId的对象:
const originalArray = [ { actionType: 10, orderItemId: "3205ae52-ab00-4823-a004-da0cda639065", productComponentAction:{ productComponent:{ offerId: 10002839, parentOfferId: 10003058, adoptableProdCompId: undefined } } }, { actionType: 10, orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae", productComponentAction:{ productComponent:{ offerId: 10002839, parentOfferId: 10003058, adoptableProdCompId: undefined } } } ]; // 用reduce遍历数组,把每个offerId对应的对象存入Map(重复的会被覆盖) const uniqueMap = originalArray.reduce((acc, item) => { const offerId = item.productComponentAction.productComponent.offerId; acc.set(offerId, item); return acc; }, new Map()); // 把Map的values转换成数组 const uniqueArray = Array.from(uniqueMap.values()); console.log(uniqueArray);
额外提示
如果你的数组中可能存在offerId为undefined或者嵌套属性缺失的情况,可以在代码里加个可选链判断,避免抛出错误:
const offerId = item.productComponentAction?.productComponent?.offerId; if (offerId !== undefined && !seenOfferIds.has(offerId)) { // ...逻辑 }
这样能让代码更健壮,适配更多边界情况。
内容的提问来源于stack exchange,提问作者ajay dixit
相关产品推荐
相关产品推荐

