如何按deliveryNumber对对象数组去重并将note合并为数组存储
实现思路
- 用
Map结构作为临时缓存,以deliveryNumber作为唯一键存储合并中的对象,保证查找效率 - 遍历原始数组的每一项元素:
- 首次遇到对应
deliveryNumber时初始化缓存条目,原有非空notes直接转为单元素数组,空值/Null保持为Null - 重复遇到同
deliveryNumber条目时,先合并非空notes到缓存条目的notes数组中,再逐字段对比,用当前条目的非空(排除Null、空字符串)字段值覆盖缓存中的旧值,实现最新非空值优先
- 首次遇到对应
- 遍历完成后将Map缓存的值集合转为数组,即为最终结果
代码实现(JavaScript)
function mergeDeliveryList(rawData) { const cache = new Map() for (const item of rawData) { const { deliveryNumber, notes, ...restFields } = item // 不存在对应单号时初始化缓存 if (!cache.has(deliveryNumber)) { const initItem = { ...item } // 处理notes转数组 initItem.notes = notes ? [notes] : null cache.set(deliveryNumber, initItem) continue } // 已存在时合并 const existItem = cache.get(deliveryNumber) // 合并notes if (notes) { existItem.notes = existItem.notes || [] existItem.notes.push(notes) } // 覆盖非空的其他字段 Object.keys(restFields).forEach(field => { const currentVal = restFields[field] if (currentVal !== null && currentVal !== '') { existItem[field] = currentVal } }) } // 转成数组输出 return Array.from(cache.values()) } // 测试示例 const rawData = [ { "deliveryNumber": "0000001", "deliveryDate": "2021-10-01T00:00:00.000Z", "dateBeginProcess": null, "dateFinishedProcess": null, "status": "", "notes": "Note 1" }, { "deliveryNumber": "0000001", "deliveryDate": "2021-10-01T00:00:00.000Z", "dateBeginProcess": null, "dateFinishedProcess": null, "status": "Ready", "notes": "Note 2" }, { "deliveryNumber": "0000002", "deliveryDate": "2021-10-01T14:21:00.000Z", "dateBeginProcess": null, "dateFinishedProcess": null, "status": "Ready", "notes": null } ] console.log(mergeDeliveryList(rawData))
输出说明
上述代码运行后输出结果完全匹配需求的期望结构,非空字段优先级、notes合并规则均符合要求。
内容的提问来源于stack exchange,提问作者sjohnston00
相关产品推荐
相关产品推荐

