React组件中如何判断MaterialOnTheFly对象是否存在重复?
解决方案
先明确你之前两次尝试的问题:
- 第一次for循环逻辑错误:只要找到一个匹配的composition就返回true,但我们需要的是所有composition都完全匹配才能判定MOF重复,而非单个匹配。
- 第二次every的思路正确,但遗漏了
compositions为undefined的边界处理,且未考虑是否需要忽略composition的顺序差异。
以下分两种常见场景给出高效实现:
场景1:要求compositions顺序完全一致
如果两个MOF的compositions必须按相同顺序排列且每个元素匹配,可结合every做严格校验:
const isDuplicateMOF = (existingMOFs: MaterialOnTheFly[], newMOF: MaterialOnTheFly): boolean => { return existingMOFs.some(existingMOF => { // 校验manufactureDetail唯一标识 if (existingMOF.manufactureDetail.manufactureDetailPublicId !== newMOF.manufactureDetail.manufactureDetailPublicId) { return false; } // 处理compositions为undefined的情况,转为空数组避免报错 const existingComps = existingMOF.compositions || []; const newComps = newMOF.compositions || []; if (existingComps.length !== newComps.length) { return false; } // 遍历所有composition,确保每一项都匹配 return existingComps.every((existingComp, index) => { const newComp = newComps[index]; // 用rawMaterialPublicId而非名字校验,避免重名导致误判 return existingComp.percentage === newComp.percentage && existingComp.rawMaterial.rawMaterialPublicId === newComp.rawMaterial.rawMaterialPublicId; }); }); };
场景2:compositions顺序不影响判定(仅需元素集合一致)
如果两个MOF的compositions只要元素相同(不管顺序)就算重复,需先对数组排序再对比:
const isDuplicateMOF = (existingMOFs: MaterialOnTheFly[], newMOF: MaterialOnTheFly): boolean => { return existingMOFs.some(existingMOF => { if (existingMOF.manufactureDetail.manufactureDetailPublicId !== newMOF.manufactureDetail.manufactureDetailPublicId) { return false; } const existingComps = existingMOF.compositions || []; const newComps = newMOF.compositions || []; if (existingComps.length !== newComps.length) { return false; } // 按rawMaterialPublicId和percentage排序,消除顺序差异 const sortCompositions = (comps: typeof existingComps) => [...comps].sort((a, b) => { const idCompare = a.rawMaterial.rawMaterialPublicId.localeCompare(b.rawMaterial.rawMaterialPublicId); if (idCompare !== 0) return idCompare; return a.percentage - b.percentage; }); const sortedExisting = sortCompositions(existingComps); const sortedNew = sortCompositions(newComps); // 排序后执行严格对比 return sortedExisting.every((existingComp, index) => { const newComp = sortedNew[index]; return existingComp.percentage === newComp.percentage && existingComp.rawMaterial.rawMaterialPublicId === newComp.rawMaterial.rawMaterialPublicId; }); }); };
核心优化说明
- 优先使用
rawMaterialPublicId校验:相比名称,唯一标识能避免重名导致的误判,准确性更高。 - 边界处理:通过
|| []将undefined的compositions转为空数组,避免长度对比和遍历时的类型错误。 - 顺序兼容:针对元素集合一致但顺序不同的场景,排序后再对比能确保判定逻辑符合业务需求。
内容的提问来源于stack exchange,提问作者Federico Giannini
相关产品推荐
相关产品推荐

