JavaScript中数组推入对象时去重并更新属性值的实现方法
问题分析
你原有代码存在以下几个核心问题,导致无法实现预期效果:
- 缺少更新逻辑:当前代码仅在目标条目不存在于
newProductList时才执行推入操作,若条目已存在不会触发旧数据更新,因此旧的quantity值一直保留 - 唯一匹配规则不严谨:你示例中的重复条目以
Id、Product、Company三个字段完全一致为判定标准,但你现有代码不管是查询myList还是判断重复都只校验了Product单个字段,容易出现误判 - 初始查询逻辑错误:
myList的查询条件写为Product === index,如果index是遍历索引的话,和Product业务字段匹配的逻辑不符合你的需求,需要调整为实际的业务匹配规则
修正后的实现代码
核心逻辑调整为:先判断目标条目是否已存在于数组中,存在则直接更新对应条目,不存在才推入新数据:
if(event.target.value.trim() !== '') { // 此处替换为你实际从myList匹配条目的业务逻辑 const searchObj = this.myList.find(({ Id, Product, Company }) => Id === currentId && Product === currentProduct && Company === currentCompany ); if (searchObj) { const resultVal = { ...searchObj, quantity: parseInt(event.target.value) }; // 按三个联合字段判断新数组中是否存在同一条目 const existIndex = this.newProductList.findIndex(e => e.Id === resultVal.Id && e.Product === resultVal.Product && e.Company === resultVal.Company ); if (existIndex > -1) { // 条目已存在,直接更新对应位置的整条数据 this.newProductList[existIndex] = resultVal; } else { // 条目不存在,推入新数据 this.newProductList.push(resultVal); } } }
大数据量场景优化方案
如果需要处理的数组条目超过千条,每次findIndex遍历性能较低,可以用Map做缓存优化,自动覆盖重复key对应的值:
// 初始化时把已有数组转成Map,以三个字段拼接的唯一值作为key const productMap = new Map( this.newProductList.map(item => [`${item.Id}-${item.Company}-${item.Product}`, item]) ); if(event.target.value.trim() !== '') { const searchObj = this.myList.find(/* 你的匹配逻辑 */); if (searchObj) { const resultVal = { ...searchObj, quantity: parseInt(event.target.value) }; const uniqueKey = `${resultVal.Id}-${resultVal.Company}-${resultVal.Product}`; // Map.set会自动覆盖已存在的key对应的值,不用手动判断是否存在 productMap.set(uniqueKey, resultVal); // 同步更新原数组 this.newProductList = Array.from(productMap.values()); } }
内容的提问来源于stack exchange,提问作者starboy The
相关产品推荐
相关产品推荐

