Bjarke Andersen Bjarke Andersen - 1 year ago 58
Javascript Question

Merging by id correctly but get empty object - Javascript

I have two arrays that needs to be merged by id (sourceID), which seems to be done, but both imagesTest objects return empty. Now sure what I am doing wrong here?

My code looks like this:



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)




Answer Source

The problem is that in eventsToBeInserted1 the sourceId is defined as an array: sourceID: [1].

Either change it to be defined as a regular int: sourceID: 1

or change the merge function:

const eventsToBeInserted = eventsToBeInserted1.map(
  event => Object.assign({}, event, {
    imagesTest: imagesTest
      .filter(img => img.sourceID === event.sourceID[0])
      .map(img => img.name)
  }))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download