JavaScript实现两个数组相同日期的数据合并方案
合并两个数组中同日期的图片数据
可以通过以下步骤实现需求:
- 将两个数组合并为一个数组
- 以
date为键对数据分组,合并对应日期下的images数组 - 将分组结果转换为目标格式的数组
实现代码
const list1 = [{ date: "2022-10-01", images: [{image: "01"}, {image: "02"}, {image: "03"}] }] const list2 = [{ date: "2022-10-01", images: [{ image: "04"}] }, {date: "2022-10-02", images: [{image: "05"}, {image: "06"}, { image: "07"}] } ] // 合并数组并处理日期分组与图片合并 const mergedResult = [...list1, ...list2].reduce((acc, current) => { const existingItem = acc.find(item => item.date === current.date); if (existingItem) { existingItem.images = [...existingItem.images, ...current.images]; } else { acc.push({...current}); } return acc; }, []); console.log(mergedResult);
代码说明
[...list1, ...list2]:将两个输入数组合并为新数组,避免修改原数据reduce方法:遍历合并后的数组,用累加器acc存储最终结果- 对每个元素,通过
find检查累加器中是否存在相同日期的项:- 存在则将当前元素的
images数组合并到已有项的images中 - 不存在则将当前元素的副本添加到累加器中
- 存在则将当前元素的
- 最终累加器即为按日期合并后的目标数组
内容的提问来源于stack exchange,提问作者corete
相关产品推荐
相关产品推荐

