我有两个需要通过id(sourceID)合并的数组,这似乎已经完成,但两个imagesTest对象都返回空。现在确定我在做错了什么?
我的代码如下所示:
const eventsToBeInserted1 = [{
name: 'Katy Perry',
slug: 'katy-perry',
sourceID: [1],
tags: ['music', 'jazz'],
images1: ['picture_perry_1', 'picture_perry_2']
},
{
name: 'Lukas Graham',
slug: 'lukas-graham',
sourceID: [2],
tags: ['rock', 'techno'],
images1: ['picture_graham_1', 'picture_graham_2']
}
]
const imagesTest = [{
sourceID: 1,
images: ['picture_perry.jpg']
},
{
sourceID: 2,
images: ['picture_graham.jpg']
}
]
const eventsToBeInserted = eventsToBeInserted1.map(
event => Object.assign({}, event, {
imagesTest: imagesTest
.filter(img => img.sourceID === event.sourceID)
.map(img => img.name)
}))
console.log(eventsToBeInserted)
答案 0 :(得分:2)
问题在于eventsToBeInserted1
sourceId
被定义为数组:sourceID: [1]
。
将其更改为定义为常规int:sourceID: 1
或更改合并功能:
const eventsToBeInserted = eventsToBeInserted1.map(
event => Object.assign({}, event, {
imagesTest: imagesTest
.filter(img => img.sourceID === event.sourceID[0])
.map(img => img.name)
}))