如何使用.map和.find合并数组,避免结果重复生成?
问题解决:基于customerLOB.code合并数组避免重复条目
问题原因
你的代码出现重复条目的核心问题有两个:
- 错误用
map执行副作用操作:map的设计目的是转换数组,你却在回调里做push操作,若数组存在重复code,就会多次触发添加; - 错误合并数组:用对象展开符
{...retrieveCondition.conditions, ...item.conditions}合并数组,会把数组索引作为对象键,得到的是对象而非合并后的数组元素集合,逻辑上的重复匹配会进一步导致重复添加。
解决方案
先将array2转换成以customerLOB.code为键的映射表,实现快速查找对应code的conditions,再遍历array1合并数据,确保每个code只处理一次:
const array1 = [ { conditions: [{ name: "xxx", id: "1" }], customerLOB: { code: "A1" }, }, { conditions: [{ name: "yyy", id: "1" }], customerLOB: { code: "A2" }, }, { conditions: [{ name: "zzzz", id: "1" }], customerLOB: { code: "A3" }, }, ]; const array2 = [ { conditions: [{ name: "mmmm", id: "1" }], customerLOB: { code: "A1" }, }, { conditions: [{ name: "nnnn", id: "1" }], customerLOB: { code: "A2" }, }, { conditions: [{ name: "oooo", id: "1" }], customerLOB: { code: "A3" }, }, ]; // 构建array2的code与conditions映射表,自动合并同code的多组conditions const lobMap = array2.reduce((acc, curr) => { const code = curr.customerLOB.code; acc[code] = (acc[code] || []).concat(curr.conditions); return acc; }, {}); // 遍历array1,合并对应code的conditions const finalList = array1.map(item => { const matchedConditions = lobMap[item.customerLOB.code] || []; // 若仅需合并后的conditions数组,直接返回 [...item.conditions, ...matchedConditions] return { ...item, conditions: [...item.conditions, ...matchedConditions] }; }); console.log(finalList);
代码说明
- 映射表构建:用
reduce将array2转为{ code: [conditions数组] }结构,即使array2存在重复code条目,也会自动合并对应conditions; - 合并逻辑:遍历
array1时,通过映射表以O(1)时间找到对应code的conditions,用数组扩展运算符合并两个数组,确保每个code仅生成一条结果; - 灵活调整:若不需要保留原对象的其他属性,可直接返回合并后的
conditions数组,删除...item即可。
内容的提问来源于stack exchange,提问作者Nancy
相关产品推荐
相关产品推荐

