我想在数组中组合具有相同日期的数据。我不够好,所以我想不出一个代码来让它像结果一样出现如果你能帮我,我将不胜感激
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"}]
}
]
result = [{
date: "2022-10-01",
images: [{image: "01"}, {image: "02"}, {image: "03"}, {image: "04"}]
},
{
date: "2022-10-02",
images: [{image: "05"}, {image: "06"}, {image: "07"}]
}
]
您可以开始连接list1
和list2
。
然后,您可以迭代整个数组,并为每个项检查是否已经在结果中存储了一个具有相同日期值的对象。
如果是这种情况,则concat
是该项目的图像数组,否则push
是结果中的项目。
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 expectedResult = [{
date: "2022-10-01",
images: [{
image: "01"
}, {
image: "02"
}, {
image: "03"
}, {
image: "04"
}]
},
{
date: "2022-10-02",
images: [{
image: "05"
}, {
image: "06"
}, {
image: "07"
}]
}
]
const both = list1.concat(list2)
const result = []
for (const obj of both) {
const index = result.findIndex(r => r.date === obj.date)
if (index >= 0) {
result[index].images = result[index].images.concat(obj.images)
} else {
result.push(obj)
}
}
console.log(result)
console.log(JSON.stringify(result) === JSON.stringify(expectedResult))