TypeScript实现数组对象按属性键值匹配筛选生成指定结构数组
实现方案
原有代码问题
- 错误使用Buffer类型的
content字段做匹配依据:Buffer是引用类型,不同引用下即使二进制内容完全一致,===比较也会返回false,无法匹配成功 - 比较逻辑错误:直接将
map返回的数组和单个值做===比较,永远无法得到预期结果 - 缺失字段合并逻辑,没有把匹配到的患者姓名组装到最终结果项里
正确代码
首先明确变量对应关系:
aux(即代码中this.namePatient):键为correlative编号、值为对应患者姓名的键值对对象- 附件数组(即代码中
attachment):每个元素包含correlative编号、PDF Buffer内容两个字段
interface bodyEmailSent { correlative: string; content: Buffer; name_Patient: string; } const newArr: bodyEmailSent[] = []; for (const item of attachment) { // 注意:如果你的附件对象里编号字段名是correlativo_solicitud,替换下方的correlative即可 const corrCode = item.correlative; const patientName = this.namePatient[corrCode]; if (patientName) { newArr.push({ correlative: corrCode, content: item.content, name_Patient: patientName }) } }
如果你的this.namePatient是数组结构而非键值对对象,将匹配逻辑替换为以下写法即可:
for (const item of attachment) { const corrCode = item.correlative; // 按aux数组的实际字段名调整匹配条件 const matchedPatient = this.namePatient.find(p => p.correlative === corrCode); if (matchedPatient) { newArr.push({ correlative: corrCode, content: item.content, name_Patient: matchedPatient.name_Patient // 按实际姓名字段名调整 }) } }
匹配必须使用唯一的correlative编号作为关联键,不要用二进制Buffer内容做匹配条件。
内容的提问来源于stack exchange,提问作者Izlia
相关产品推荐
相关产品推荐

